<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Include DB connection
include __DIR__ . '/../inc/db.php'; // Adjust path if necessary

header('Content-Type: application/json');

$action = $_REQUEST['action'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id      = $_POST['id'] ?? null;
    $name    = trim($_POST['name'] ?? '');
    $email   = trim($_POST['email'] ?? '');
    $phone   = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $status  = $_POST['status'] ?? 'active';

    // CREATE
    if ($action === 'Create') {
        if (empty($name) || empty($phone) || empty($address)) {
            echo json_encode(["status" => "error", "message" => "All required fields must be filled."]);
            exit;
        }

        // Check if phone already exists
        $stmt = $conn->prepare("SELECT id FROM customers WHERE phone = ?");
        $stmt->bind_param("s", $phone);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            echo json_encode(["status" => "error", "message" => "Phone number already exists."]);
            exit;
        }

        $stmt = $conn->prepare("INSERT INTO customers (name, email, phone, address, status) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("sssss", $name, $email, $phone, $address, $status);
        
        if ($stmt->execute()) {
            $customerId = $conn->insert_id;
            echo json_encode([
                'status' => 'success',
                'message' => 'Customer added successfully.',
                'customer' => [
                    'id' => $customerId,
                    'name' => $name,
                    'phone' => $phone
                ]
            ]);
           // echo json_encode(["status" => "success", "message" => "Customer created successfully."]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to create customer.", "error" => $stmt->error]);
        }
        exit;
    }

    // UPDATE
    if ($action === 'Update' && $id) {
        if (empty($name) || empty($phone) || empty($address)) {
            echo json_encode(["status" => "error", "message" => "All required fields must be filled."]);
            exit;
        }

        // Check if phone already exists for other records (except the current one being updated)
        $stmt = $conn->prepare("SELECT id FROM customers WHERE phone = ? AND id != ?");
        $stmt->bind_param("si", $phone, $id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            echo json_encode(["status" => "error", "message" => "Phone number already exists."]);
            exit;
        }

        $stmt = $conn->prepare("UPDATE customers SET name=?, email=?, phone=?, address=?, status=?, updated_at=CURRENT_TIMESTAMP WHERE id=?");
        $stmt->bind_param("sssssi", $name, $email, $phone, $address, $status, $id);

        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Customer updated successfully."]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to update customer.", "error" => $stmt->error]);
        }
        exit;
    }

    // DELETE
    if ($action === 'Delete' && $id) {
        $stmt = $conn->prepare("SELECT id FROM customers WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            echo json_encode(["status" => "error", "message" => "Customer not found."]);
            exit;
        }

        $stmt = $conn->prepare("DELETE FROM customers WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Customer deleted successfully."]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to delete customer.", "error" => $stmt->error]);
        }
        exit;
    }

    // SELECT SINGLE
    if ($action === 'Select' && $id) {
        $stmt = $conn->prepare("SELECT id, name, email, phone, address, status FROM customers WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            echo json_encode(["status" => "error", "message" => "Customer not found."]);
            exit;
        }

        $customer = $result->fetch_assoc();
        echo json_encode($customer);
        exit;
    }

    // TOGGLE STATUS
    if ($action === 'ToggleStatus' && $id) {
        $stmt = $conn->prepare("SELECT status FROM customers WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();

        if (!$result) {
            echo json_encode(["status" => "error", "message" => "Customer not found."]);
            exit;
        }

        $new_status = ($result['status'] === 'active') ? 'inactive' : 'active';
        $stmt = $conn->prepare("UPDATE customers SET status = ? WHERE id = ?");
        $stmt->bind_param("si", $new_status, $id);

        if ($stmt->execute()) {
            echo json_encode(["status" => "success", "message" => "Customer status updated.", "new_status" => $new_status]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to update status.", "error" => $stmt->error]);
        }
        exit;
    }
}
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    if ($_GET['action'] == 'getCustomers') {
        // Query to get customers from the database
        $query = "SELECT id, name, phone FROM customers WHERE status = 'active' ORDER BY name ASC";
        $result = $conn->query($query);
        
        // Check if any customers are found
        if ($result->num_rows > 0) {
            $customers = [];
            while ($row = $result->fetch_assoc()) {
                $customers[] = [
                    'id' => $row['id'],
                    'name' => $row['name'],
                    'phone' => $row['phone']
                ];
            }
            echo json_encode(['status' => 'success', 'customers' => $customers]);
        } else {
            echo json_encode(['status' => 'success', 'customers' => []]);
        }
    }
}
?>
