<?php
// --- SETUP AND INCLUDES ---
require_once '../config/cors.php';
require_once '../config/database.php';

// --- DATABASE CONNECTION ---
$database = new Database();
$db = $database->getConnection();

// --- HTTP METHOD ROUTING ---
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        try {
            $id = isset($_GET['id']) ? filter_var($_GET['id'], FILTER_VALIDATE_INT) : null;
            
            if ($id) {
                $stmt = $db->prepare("SELECT * FROM coupons WHERE id = :id");
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
            } else {
                $stmt = $db->prepare("SELECT * FROM coupons ORDER BY created_at DESC");
            }
            
            $stmt->execute();
            $data = $id ? $stmt->fetch(PDO::FETCH_ASSOC) : $stmt->fetchAll(PDO::FETCH_ASSOC);

            http_response_code(200);
            echo json_encode(['success' => true, 'coupons' => $data]);

        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Database query failed: ' . $e->getMessage()]);
        }
        break;

    case 'POST':
        $data = json_decode(file_get_contents('php://input'), true);
        
        // --- VALIDATION ---
        if (empty($data['code']) || empty($data['type']) || !isset($data['value'])) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Fields code, type, and value are required.']);
            exit;
        }
        
        try {
            $sql = "INSERT INTO coupons (code, type, value, min_order_value, usage_limit, expires_at, active) 
                    VALUES (:code, :type, :value, :min_order_value, :usage_limit, :expires_at, :active)";
            $stmt = $db->prepare($sql);
            
            // Convert boolean `active` status to 1 or 0 for the database
            $active = isset($data['active']) && $data['active'] ? 1 : 0;
            
            $stmt->execute([
                ':code'             => htmlspecialchars(strip_tags($data['code'])),
                ':type'             => htmlspecialchars(strip_tags($data['type'])),
                ':value'            => filter_var($data['value'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION),
                ':min_order_value'  => isset($data['min_order_value']) ? filter_var($data['min_order_value'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION) : null,
                ':usage_limit'      => isset($data['usage_limit']) ? filter_var($data['usage_limit'], FILTER_SANITIZE_NUMBER_INT) : null,
                ':expires_at'       => $data['expires_at'] ?? null,
                ':active'           => $active
            ]);
            
            http_response_code(201);
            echo json_encode([
                'success' => true, 
                'message' => 'Coupon created successfully.', 
                'id' => $db->lastInsertId()
            ]);

        } catch (PDOException $e) {
            // Check for duplicate coupon code error
            if ($e->errorInfo[1] == 1062) {
                http_response_code(409); // 409 Conflict
                echo json_encode(['success' => false, 'error' => 'This coupon code already exists.']);
            } else {
                http_response_code(500);
                echo json_encode(['success' => false, 'error' => 'Failed to create coupon: ' . $e->getMessage()]);
            }
        }
        break;

    case 'PUT':
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (empty($data['id'])) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Coupon ID is required.']);
            exit;
        }
        
        try {
            // --- SECURITY FIX: Whitelist of allowed fields to prevent mass assignment ---
            $allowedFields = ['code', 'type', 'value', 'min_order_value', 'usage_limit', 'expires_at', 'active'];
            $updateParts = [];
            $params = [':id' => $data['id']];

            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $updateParts[] = "$field = :$field";
                    if ($field === 'active') {
                        $params[":$field"] = $data[$field] ? 1 : 0;
                    } else {
                        $params[":$field"] = htmlspecialchars(strip_tags($data[$field]));
                    }
                }
            }
            // --- END OF SECURITY FIX ---

            if (empty($updateParts)) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'No valid fields provided to update.']);
                exit;
            }
            
            $sql = "UPDATE coupons SET " . implode(", ", $updateParts) . " WHERE id = :id";
            $stmt = $db->prepare($sql);
            
            if ($stmt->execute($params)) {
                http_response_code(200);
                echo json_encode(['success' => true, 'message' => 'Coupon updated successfully.']);
            } else {
                 http_response_code(500);
                 echo json_encode(['success' => false, 'error' => 'Failed to execute the update statement.']);
            }

        } catch (PDOException $e) {
            if ($e->errorInfo[1] == 1062) {
                http_response_code(409);
                echo json_encode(['success' => false, 'error' => 'This coupon code is already in use by another coupon.']);
            } else {
                http_response_code(500);
                echo json_encode(['success' => false, 'error' => 'Failed to update coupon: ' . $e->getMessage()]);
            }
        }
        break;

   case 'DELETE':
        $data = json_decode(file_get_contents('php://input'), true);
        
        // --- FIX: Validate as a string, not an integer ---
        $id = isset($data['id']) ? trim($data['id']) : null;
        
        if (!$id) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'A valid Coupon ID is required in the request body.']);
            exit;
        }
        
        try {
            $stmt = $db->prepare("DELETE FROM coupons WHERE id = :id");
            // --- FIX: Bind as a string parameter ---
            $stmt->bindParam(':id', $id, PDO::PARAM_STR);
            
            if ($stmt->execute()) {
                if ($stmt->rowCount() > 0) {
                    http_response_code(200);
                    echo json_encode(['success' => true, 'message' => 'Coupon deleted successfully.']);
                } else {
                    http_response_code(444);
                    echo json_encode(['success' => false, 'error' => 'Coupon not found with that ID.']);
                }
            } else {
                throw new Exception('Failed to execute delete statement.');
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Failed to delete coupon: ' . $e->getMessage()]);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'Method Not Allowed']);
        break;
}
?>

