File manager - Edit - /home/webapp69.cm.in.th/u69319090033/Shop/api/orders.php
Back
<?php header('Content-Type: application/json; charset=utf-8'); require_once '../db.php'; if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success' => false, 'message' => 'กรุณาเข้าสู่ระบบก่อน']); exit; } $method = $_SERVER['REQUEST_METHOD']; $userId = (int)$_SESSION['user_id']; $userRole = $_SESSION['role'] ?? 'user'; $isAdmin = ($userRole === 'admin'); // ─── POST: สร้างคำสั่งซื้อใหม่ (พร้อม slip) ───────────────────────────────── if ($method === 'POST') { $input = json_decode(file_get_contents('php://input'), true); $paymentMethod = trim($input['payment_method'] ?? 'promptpay'); $shippingAddress = trim($input['shipping_address'] ?? ''); $totalAmount = (float)($input['total_amount'] ?? 0); $paymentSlip = trim($input['payment_slip'] ?? ''); // path จาก upload_slip.php $cartItems = $input['cart_items'] ?? []; if ($totalAmount <= 0 || empty($cartItems)) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'ข้อมูลคำสั่งซื้อไม่ถูกต้อง']); exit; } // ถ้าไม่ใช่ COD ต้องมีสลิป if ($paymentMethod !== 'cod' && empty($paymentSlip)) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'กรุณาแนบสลิปการโอนเงินก่อนยืนยันคำสั่งซื้อ']); exit; } // เริ่ม Transaction $conn->begin_transaction(); try { // บันทึก Order $stmt = $conn->prepare("INSERT INTO orders (user_id, total_amount, status, shipping_address, payment_method, payment_slip) VALUES (?, ?, 'pending', ?, ?, ?)"); $stmt->bind_param('idsss', $userId, $totalAmount, $shippingAddress, $paymentMethod, $paymentSlip); if (!$stmt->execute()) throw new Exception('ไม่สามารถบันทึกคำสั่งซื้อได้'); $orderId = $conn->insert_id; $stmt->close(); // บันทึก Order Items $stmtItem = $conn->prepare("INSERT INTO order_items (order_id, product_id, quantity, price_at_purchase) VALUES (?, ?, ?, ?)"); foreach ($cartItems as $item) { $pid = (int)($item['id'] ?? 0); $qty = (int)($item['qty'] ?? 1); $price = (float)($item['price'] ?? 0); if ($pid <= 0 || $qty <= 0) continue; $stmtItem->bind_param('iiid', $orderId, $pid, $qty, $price); if (!$stmtItem->execute()) throw new Exception('ไม่สามารถบันทึกรายการสินค้าได้'); } $stmtItem->close(); $conn->commit(); echo json_encode([ 'success' => true, 'message' => 'สั่งซื้อสำเร็จ! กรุณารอแอดมินตรวจสอบสลิปและอนุมัติคำสั่งซื้อ', 'order_id' => $orderId ]); } catch (Exception $e) { $conn->rollback(); http_response_code(500); echo json_encode(['success' => false, 'message' => $e->getMessage()]); } exit; } // ─── GET: ดึงรายการคำสั่งซื้อ (Admin เห็นทั้งหมด, User เห็นของตัวเอง) ───── if ($method === 'GET') { if ($isAdmin) { $stmt = $conn->prepare(" SELECT o.order_id, o.total_amount, o.status, o.payment_method, o.payment_slip, o.shipping_address, o.created_at, o.approved_at, u.full_name AS customer_name, u.email AS customer_email FROM orders o JOIN users u ON u.user_id = o.user_id ORDER BY o.created_at DESC LIMIT 100 "); $stmt->execute(); } else { $stmt = $conn->prepare(" SELECT o.order_id, o.total_amount, o.status, o.payment_method, o.payment_slip, o.shipping_address, o.created_at, o.approved_at, u.full_name AS customer_name FROM orders o JOIN users u ON u.user_id = o.user_id WHERE o.user_id = ? ORDER BY o.created_at DESC LIMIT 50 "); $stmt->bind_param('i', $userId); $stmt->execute(); } $orders = $stmt->get_result()->fetch_all(MYSQLI_ASSOC); $stmt->close(); echo json_encode(['success' => true, 'orders' => $orders]); exit; } // ─── PUT: Admin อนุมัติ / ปฏิเสธ / อัปเดตสถานะ ───────────────────────────── if ($method === 'PUT') { if (!$isAdmin) { http_response_code(403); echo json_encode(['success' => false, 'message' => 'เฉพาะแอดมินเท่านั้น']); exit; } $input = json_decode(file_get_contents('php://input'), true); $orderId = (int)($input['order_id'] ?? 0); $newStatus = trim($input['status'] ?? ''); $allowed = ['pending', 'shipping', 'delivered', 'cancelled']; if ($orderId <= 0 || !in_array($newStatus, $allowed)) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'ข้อมูลไม่ถูกต้อง']); exit; } // ถ้า approve (shipping) บันทึกเวลา if ($newStatus === 'shipping') { $stmt = $conn->prepare("UPDATE orders SET status = ?, approved_at = NOW() WHERE order_id = ?"); } else { $stmt = $conn->prepare("UPDATE orders SET status = ? WHERE order_id = ?"); } $stmt->bind_param('si', $newStatus, $orderId); if ($stmt->execute() && $stmt->affected_rows > 0) { $stmt->close(); $msg = 'อัปเดตสถานะเรียบร้อย'; if ($newStatus === 'shipping') $msg = 'อนุมัติคำสั่งซื้อเรียบร้อย กำลังจัดส่ง'; elseif ($newStatus === 'delivered') $msg = 'อัปเดตสถานะเป็น จัดส่งแล้ว'; elseif ($newStatus === 'cancelled') $msg = 'ยกเลิกคำสั่งซื้อแล้ว'; echo json_encode(['success' => true, 'message' => $msg]); } else { $stmt->close(); echo json_encode(['success' => false, 'message' => 'ไม่พบคำสั่งซื้อนี้ หรือเกิดข้อผิดพลาด']); } exit; } http_response_code(405); echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
| ver. 1.4 |
Github
|
.
| PHP 7.4.33 | Generation time: 0.24 |
proxy
|
phpinfo
|
Settings