<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

// Include database configuration
include 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        getProfile($conn);
        break;
    case 'PUT':
        updateProfile($conn, $input);
        break;
    case 'POST':
        if (isset($_POST['action']) && $_POST['action'] === 'upload_photo') {
            uploadProfilePhoto($conn);
        } else {
            updateProfile($conn, $input);
        }
        break;
    default:
        http_response_code(405);
        echo json_encode([
            'success' => false,
            'message' => 'Method not allowed'
        ]);
        break;
}

function getProfile($conn)
{
    try {
        // Get customer_id from query parameter
        if (!isset($_GET['customer_id']) || empty($_GET['customer_id'])) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Customer ID is required'
            ]);
            return;
        }

        $customer_id = $_GET['customer_id'];

        $stmt = $conn->prepare("SELECT customer_id, name, email, phone, addresses, profile_photo FROM customers WHERE customer_id = ?");
        $stmt->bind_param("s", $customer_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $customer = $result->fetch_assoc();

        if ($customer) {
            // Handle null values and provide defaults
            $response = [
                'success' => true,
                'data' => [
                    'customer_id' => $customer['customer_id'],
                    'name' => $customer['name'] ?? '',
                    'email' => $customer['email'] ?? '',
                    'phone' => $customer['phone'] ?? '',
                    'addresses' => $customer['addresses'] ?? '',
                    'profile_photo' => $customer['profile_photo'] ?? '',
                    'has_name' => !empty($customer['name']),
                    'has_phone' => !empty($customer['phone']),
                    'has_addresses' => !empty($customer['addresses']),
                    'has_profile_photo' => !empty($customer['profile_photo']),
                    'email_verified' => !empty($customer['email'])
                ]
            ];
        } else {
            http_response_code(404);
            $response = [
                'success' => false,
                'message' => 'Customer not found'
            ];
        }

        echo json_encode($response);
        $stmt->close();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Database error: ' . $e->getMessage()
        ]);
    }
}

function updateProfile($conn, $input)
{
    try {
        if (!isset($input['customer_id']) || empty($input['customer_id'])) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Customer ID is required'
            ]);
            return;
        }

        $customer_id = $input['customer_id'];
        $updates = [];
        $types = "";
        $params = [];

        // Check which fields to update
        if (isset($input['name'])) {
            $updates[] = "name = ?";
            $types .= "s";
            $params[] = $input['name'];
        }

        if (isset($input['phone'])) {
            $updates[] = "phone = ?";
            $types .= "s";
            $params[] = $input['phone'];
        }

        if (isset($input['email'])) {
            $updates[] = "email = ?";
            $types .= "s";
            $params[] = $input['email'];
        }

        if (isset($input['addresses'])) {
            $updates[] = "addresses = ?";
            $types .= "s";
            $params[] = $input['addresses'];
        }

        if (empty($updates)) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'No fields to update'
            ]);
            return;
        }

        $types .= "s";
        $params[] = $customer_id;
        $sql = "UPDATE customers SET " . implode(', ', $updates) . " WHERE customer_id = ?";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $result = $stmt->execute();

        if ($result && $stmt->affected_rows > 0) {
            // Fetch updated data
            $stmt->close();
            $stmt = $conn->prepare("SELECT customer_id, name, email, phone, profile_photo FROM customers WHERE customer_id = ?");
            $stmt->bind_param("s", $customer_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $customer = $result->fetch_assoc();

            echo json_encode([
                'success' => true,
                'message' => 'Profile updated successfully',
                'data' => [
                    'customer_id' => $customer['customer_id'],
                    'name' => $customer['name'] ?? '',
                    'email' => $customer['email'] ?? '',
                    'phone' => $customer['phone'] ?? '',
                    'profile_photo' => $customer['profile_photo'] ?? '',
                    'has_name' => !empty($customer['name']),
                    'has_phone' => !empty($customer['phone']),
                    'has_profile_photo' => !empty($customer['profile_photo']),
                    'email_verified' => !empty($customer['email'])
                ]
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'No changes made or customer not found'
            ]);
        }

        $stmt->close();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Database error: ' . $e->getMessage()
        ]);
    }
}

function uploadProfilePhoto($conn)
{
    try {
        if (!isset($_POST['customer_id']) || empty($_POST['customer_id'])) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Customer ID is required'
            ]);
            return;
        }

        if (!isset($_FILES['profile_photo']) || $_FILES['profile_photo']['error'] !== UPLOAD_ERR_OK) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'No valid image uploaded'
            ]);
            return;
        }

        $customer_id = $_POST['customer_id'];
        $file = $_FILES['profile_photo'];

        // Validate file type
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if (!in_array($file['type'], $allowed_types)) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Invalid file type. Only JPEG, PNG, GIF, and WebP are allowed.'
            ]);
            return;
        }

        // Validate file size (max 5MB)
        if ($file['size'] > 5 * 1024 * 1024) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'File size too large. Maximum size is 5MB.'
            ]);
            return;
        }

        // Create uploads directory if it doesn't exist
        $upload_dir = 'uploads/profile_photos/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        // Generate unique filename
        $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'profile_' . $customer_id . '_' . time() . '.' . $file_extension;
        $file_path = $upload_dir . $filename;

        // Move uploaded file
        if (move_uploaded_file($file['tmp_name'], $file_path)) {
            // Delete old profile photo if exists
            $stmt = $conn->prepare("SELECT profile_photo FROM customers WHERE customer_id = ?");
            $stmt->bind_param("s", $customer_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $old_data = $result->fetch_assoc();

            if ($old_data && !empty($old_data['profile_photo']) && file_exists($old_data['profile_photo'])) {
                unlink($old_data['profile_photo']);
            }
            $stmt->close();

            // Update database with new photo path
            $stmt = $conn->prepare("UPDATE customers SET profile_photo = ? WHERE customer_id = ?");
            $stmt->bind_param("ss", $file_path, $customer_id);
            $result = $stmt->execute();

            if ($result) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Profile photo uploaded successfully',
                    'data' => [
                        'profile_photo' => $file_path,
                        'photo_url' => 'https://lgdash.conceptpoint.africa/' . $file_path // Replace with your actual domain
                    ]
                ]);
            } else {
                // Delete uploaded file if database update fails
                unlink($file_path);
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to update database'
                ]);
            }
            $stmt->close();
        } else {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'message' => 'Failed to upload file'
            ]);
        }
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Upload error: ' . $e->getMessage()
        ]);
    }
}

$conn->close();
