File size: 2,179 Bytes
c7257f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
require_once 'config.php';

// GET all products
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $stmt = $pdo->query("SELECT * FROM products");
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($products);
}

// POST new product (Admin only)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once 'require_auth.php'; // This now includes admin role checking
    
    $data = json_decode(file_get_contents("php://input"));
    
    $stmt = $pdo->prepare("INSERT INTO products (name, description, price, stock, image_url) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$data->name, $data->description, $data->price, $data->stock, $data->image_url]);
    
    $product_id = $pdo->lastInsertId();
    $stmt = $pdo->query("SELECT * FROM products WHERE id = $product_id");
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode($product);
}

// UPDATE product (Admin only)
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    require_once 'require_auth.php'; // This now includes admin role checking
    
    $data = json_decode(file_get_contents("php://input"));
    $id = $_GET['id'] ?? null;
    
    if($id) {
        $stmt = $pdo->prepare("UPDATE products SET name = ?, description = ?, price = ?, stock = ?, image_url = ? WHERE id = ?");
        $stmt->execute([$data->name, $data->description, $data->price, $data->stock, $data->image_url, $id]);
        
        echo json_encode(array("success" => true, "message" => "Product updated"));
    } else {
        http_response_code(400);
        echo json_encode(array("success" => false, "message" => "Product ID required"));
    }
}

// DELETE product (Admin only)
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    require_once 'require_auth.php'; // This now includes admin role checking
    
    $id = $_GET['id'] ?? null;
    
    if($id) {
        $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?");
        $stmt->execute([$id]);
        
        echo json_encode(array("success" => true, "message" => "Product deleted"));
    } else {
        http_response_code(400);
        echo json_encode(array("success" => false, "message" => "Product ID required"));
    }
}
?>