<?php
/**
 * Simple Customers API
 * Methods: GET, POST, PUT, DELETE
 */

// Start session
session_start();

// Include database connection
require_once '../controlls/functions.php';

// Set response headers
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

/**
 * Send JSON response
 */
function sendResponse($success, $message, $data = null) {
    $response = array(
        'success' => (bool)$success,
        'message' => $message
    );
    
    if ($data !== null) {
        $response['data'] = $data;
    }
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit();
}

/**
 * Check if user is logged in
 */
function checkAuth() {
    if (!isset($_SESSION['user_login'])) {
        sendResponse(false, 'Authentication required');
    }
    return $_SESSION['user_login'];
}

/**
 * Validate email format
 */
function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

/**
 * Hash password securely
 */
function hashPassword($password) {
    return password_hash($password, PASSWORD_DEFAULT);
}

// Get request method
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        
        // ==================== GET - Retrieve Customers ====================
        case 'GET':
            if (isset($_GET['id'])) {
                // Get single customer
                $customer_id = intval($_GET['id']);
                
                $stmt = $conn->prepare("
                    SELECT id, name, email, phone_number, role, nation_code, avatar, 
                           place, adress, status, created_at, updated_at
                    FROM users
                    WHERE id = :id
                    LIMIT 1
                ");
                $stmt->execute([':id' => $customer_id]);
                $customer = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($customer) {
                    sendResponse(true, 'Customer retrieved successfully', $customer);
                } else {
                    sendResponse(false, 'Customer not found');
                }
                
            } else {
                // Get all customers
                $where = array();
                $params = array();
                
                // Filter by role
                if (isset($_GET['role']) && !empty($_GET['role'])) {
                    $where[] = "role = :role";
                    $params[':role'] = $_GET['role'];
                }
                
                // Filter by status
                if (isset($_GET['status']) && !empty($_GET['status'])) {
                    $where[] = "status = :status";
                    $params[':status'] = $_GET['status'];
                }
                
                // Search by name or email
                if (isset($_GET['search']) && !empty($_GET['search'])) {
                    $where[] = "(name LIKE :search OR email LIKE :search OR phone_number LIKE :search)";
                    $params[':search'] = '%' . $_GET['search'] . '%';
                }
                
                $where_sql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
                
                $sql = "
                    SELECT id, name, email, phone_number, role, nation_code, avatar, 
                           place, adress, status, created_at, updated_at
                    FROM users
                    $where_sql
                    ORDER BY created_at DESC
                ";
                
                $stmt = $conn->prepare($sql);
                foreach ($params as $key => $value) {
                    $stmt->bindValue($key, $value);
                }
                $stmt->execute();
                $customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                sendResponse(true, 'Customers retrieved successfully', array(
                    'customers' => $customers,
                    'total' => count($customers)
                ));
            }
            break;
        
        // ==================== POST - Create Customer ====================
        case 'POST':
            checkAuth();
            
            // Get JSON data
            $json_input = file_get_contents('php://input');
            $input = json_decode($json_input, true);
            
            // Support form data as fallback
            if (empty($input)) {
                $input = $_POST;
            }
            
            // Validate required fields
            if (!isset($input['name']) || empty($input['name'])) {
                sendResponse(false, 'Name is required');
            }
            
            if (!isset($input['email']) || empty($input['email'])) {
                sendResponse(false, 'Email is required');
            }
            
            if (!validateEmail($input['email'])) {
                sendResponse(false, 'Invalid email format');
            }
            
            if (!isset($input['password']) || empty($input['password'])) {
                sendResponse(false, 'Password is required');
            }
            
            if (strlen($input['password']) < 6) {
                sendResponse(false, 'Password must be at least 6 characters');
            }
            
            // Check if email already exists
            $check_email = $conn->prepare("SELECT id FROM users WHERE email = :email");
            $check_email->execute([':email' => $input['email']]);
            if ($check_email->rowCount() > 0) {
                sendResponse(false, 'Email already exists');
            }
            
            // Hash password
            $hashed_password = hashPassword($input['password']);
            
            // Insert customer
            $sql = "INSERT INTO users (
                name, email, phone_number, password, role, nation_code, 
                place, adress, status
            ) VALUES (
                :name, :email, :phone_number, :password, :role, :nation_code, 
                :place, :adress, :status
            )";
            
            $stmt = $conn->prepare($sql);
            
            $stmt->bindValue(':name', $input['name']);
            $stmt->bindValue(':email', $input['email']);
            $stmt->bindValue(':phone_number', isset($input['phone_number']) ? $input['phone_number'] : null);
            $stmt->bindValue(':password', $hashed_password);
            $stmt->bindValue(':role', isset($input['role']) ? $input['role'] : 'customer');
            $stmt->bindValue(':nation_code', isset($input['nation_code']) ? $input['nation_code'] : null);
            $stmt->bindValue(':place', isset($input['place']) ? $input['place'] : null);
            $stmt->bindValue(':adress', isset($input['adress']) ? $input['adress'] : null);
            $stmt->bindValue(':status', isset($input['status']) ? $input['status'] : 'active');
            
            if ($stmt->execute()) {
                $customer_id = $conn->lastInsertId();
                sendResponse(true, 'Customer created successfully', array('customer_id' => $customer_id));
            } else {
                sendResponse(false, 'Failed to create customer');
            }
            break;
        
        // ==================== PUT - Update Customer ====================
        case 'PUT':
            checkAuth();
            
            if (!isset($_GET['id'])) {
                sendResponse(false, 'Customer ID is required');
            }
            
            $customer_id = intval($_GET['id']);
            
            // Check if customer exists
            $check = $conn->prepare("SELECT id FROM users WHERE id = :id");
            $check->execute([':id' => $customer_id]);
            
            if ($check->rowCount() === 0) {
                sendResponse(false, 'Customer not found');
            }
            
            // Get JSON data
            $json_input = file_get_contents('php://input');
            $input = json_decode($json_input, true);
            
            // Validate email if provided
            if (isset($input['email']) && !empty($input['email']) && !validateEmail($input['email'])) {
                sendResponse(false, 'Invalid email format');
            }
            
            // Build update query dynamically
            $update_fields = array();
            $params = array(':id' => $customer_id);
            
            $allowed_fields = array('name', 'email', 'phone_number', 'role', 'nation_code', 
                              'place', 'adress', 'status');
            
            foreach ($allowed_fields as $field) {
                if (isset($input[$field])) {
                    $update_fields[] = "$field = :$field";
                    $params[":$field"] = $input[$field];
                }
            }
            
            // Handle password update separately
            if (isset($input['password']) && !empty($input['password'])) {
                if (strlen($input['password']) < 6) {
                    sendResponse(false, 'Password must be at least 6 characters');
                }
                $update_fields[] = "password = :password";
                $params[':password'] = hashPassword($input['password']);
            }
            
            // Check if email is being changed and already exists
            if (isset($input['email'])) {
                $check_email = $conn->prepare("SELECT id FROM users WHERE email = :email AND id != :id");
                $check_email->execute([':email' => $input['email'], ':id' => $customer_id]);
                if ($check_email->rowCount() > 0) {
                    sendResponse(false, 'Email already exists');
                }
            }
            
            if (empty($update_fields)) {
                sendResponse(false, 'No fields to update');
            }
            
            $sql = "UPDATE users SET " . implode(', ', $update_fields) . " WHERE id = :id";
            $stmt = $conn->prepare($sql);
            
            foreach ($params as $key => $value) {
                $stmt->bindValue($key, $value);
            }
            
            if ($stmt->execute()) {
                sendResponse(true, 'Customer updated successfully', array('customer_id' => $customer_id));
            } else {
                sendResponse(false, 'Failed to update customer');
            }
            break;
        
        // ==================== DELETE - Delete Customer ====================
        case 'DELETE':
            checkAuth();
            
            if (!isset($_GET['id'])) {
                sendResponse(false, 'Customer ID is required');
            }
            
            $customer_id = intval($_GET['id']);
            
            // Prevent deleting yourself
            $user = $_SESSION['user_login'];
            if ($customer_id == $user['id']) {
                sendResponse(false, 'You cannot delete your own account');
            }
            
            // Delete customer
            $stmt = $conn->prepare("DELETE FROM users WHERE id = :id");
            $stmt->execute([':id' => $customer_id]);
            
            if ($stmt->rowCount() > 0) {
                sendResponse(true, 'Customer deleted successfully');
            } else {
                sendResponse(false, 'Customer not found');
            }
            break;
        
        default:
            sendResponse(false, 'Method not allowed');
            break;
    }
    
} catch (PDOException $e) {
    sendResponse(false, 'Database error: ' . $e->getMessage());
} catch (Exception $e) {
    sendResponse(false, 'Server error: ' . $e->getMessage());
}