<?php
/**
 * Appointments API Routes
 * 
 * Handles CRUD operations for appointments and booking management.
 */

require_once '../lib/Auth.php';
require_once '../lib/Validation.php';
require_once '../lib/Email.php';

$auth = new Auth();
$validation = new Validation();
$response = new Response();
$db = getDB();

// Get request data
$input = json_decode(file_get_contents('php://input'), true) ?? [];
$id = $_GET['id'] ?? null;
$action = $_GET['action'] ?? '';

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        if ($id) {
            // Get single appointment
            $stmt = $db->prepare("
                SELECT a.*, u.name as customer_name, u.email as customer_email, u.phone as customer_phone
                FROM appointments a 
                LEFT JOIN users u ON a.customer_id = u.id 
                WHERE a.id = ?
            ");
            $stmt->execute([$id]);
            $appointment = $stmt->fetch();
            
            if (!$appointment) {
                $response->notFound('Appointment not found');
            }
            
            $response->success($appointment);
            
        } else {
            // Get all appointments with filtering
            $page = max(1, intval($_GET['page'] ?? 1));
            $limit = min(50, max(1, intval($_GET['limit'] ?? 20)));
            $offset = ($page - 1) * $limit;
            
            $status = $_GET['status'] ?? null;
            $customer_id = $_GET['customer_id'] ?? null;
            $date_from = $_GET['date_from'] ?? null;
            $date_to = $_GET['date_to'] ?? null;
            
            $where_conditions = [];
            $params = [];
            
            if ($status) {
                $where_conditions[] = "a.status = ?";
                $params[] = $status;
            }
            
            if ($customer_id) {
                $where_conditions[] = "a.customer_id = ?";
                $params[] = $customer_id;
            }
            
            if ($date_from) {
                $where_conditions[] = "DATE(a.appointment_date) >= ?";
                $params[] = $date_from;
            }
            
            if ($date_to) {
                $where_conditions[] = "DATE(a.appointment_date) <= ?";
                $params[] = $date_to;
            }
            
            $where_clause = $where_conditions ? "WHERE " . implode(' AND ', $where_conditions) : "";
            
            // Get appointments
            $stmt = $db->prepare("
                SELECT a.*, u.name as customer_name 
                FROM appointments a 
                LEFT JOIN users u ON a.customer_id = u.id 
                $where_clause 
                ORDER BY a.appointment_date DESC, a.appointment_time DESC 
                LIMIT ? OFFSET ?
            ");
            $params[] = $limit;
            $params[] = $offset;
            $stmt->execute($params);
            $appointments = $stmt->fetchAll();
            
            // Get total count
            $stmt = $db->prepare("SELECT COUNT(*) as total FROM appointments a $where_clause");
            $count_params = array_slice($params, 0, count($params) - 2);
            $stmt->execute($count_params);
            $total = $stmt->fetch()['total'];
            
            $response->success([
                'appointments' => $appointments,
                'pagination' => [
                    'page' => $page,
                    'limit' => $limit,
                    'total' => $total,
                    'pages' => ceil($total / $limit)
                ]
            ]);
        }
        break;
        
    case 'POST':
        // Create new appointment
        $user_data = $auth->protectRoute(); // Any authenticated user can create appointments
        
        $validation_result = $validation->validateAppointment($input);
        
        if (!$validation_result['valid']) {
            $response->validationError($validation_result['errors']);
        }
        
        try {
            // Check for conflicting appointments
            $stmt = $db->prepare("
                SELECT COUNT(*) as conflict_count 
                FROM appointments 
                WHERE appointment_date = ? AND appointment_time = ? AND status IN ('scheduled', 'confirmed')
            ");
            $stmt->execute([
                $validation->sanitize($input['appointment_date']),
                $validation->sanitize($input['appointment_time'])
            ]);
            $conflict = $stmt->fetch();
            
            if ($conflict['conflict_count'] > 0) {
                $response->error('Time slot is already booked. Please choose a different time.', 409);
            }
            
            // Create appointment
            $stmt = $db->prepare("
                INSERT INTO appointments (
                    customer_id, customer_name, customer_phone, customer_email,
                    car_make, car_model, car_year, service_type,
                    appointment_date, appointment_time, status, notes,
                    county, subcounty, address, latitude, longitude, service_location,
                    estimated_price, payment_status, deposit_amount, total_amount
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $user_data['user_id'] ?? null,
                $validation->sanitize($input['customer_name']),
                $validation->sanitize($input['customer_phone']),
                $validation->sanitize($input['customer_email']),
                $validation->sanitize($input['car_make']),
                $validation->sanitize($input['car_model']),
                intval($input['car_year']),
                $validation->sanitize($input['service_type']),
                $validation->sanitize($input['appointment_date']),
                $validation->sanitize($input['appointment_time']),
                $input['status'] ?? 'pending_payment',
                $validation->sanitize($input['notes'] ?? ''),
                $validation->sanitize($input['county'] ?? ''),
                $validation->sanitize($input['subcounty'] ?? ''),
                $validation->sanitize($input['address'] ?? ''),
                $input['latitude'] ?? null,
                $input['longitude'] ?? null,
                $validation->sanitize($input['service_location'] ?? 'workshop'),
                floatval($input['estimated_price'] ?? 0.0),
                $input['payment_status'] ?? 'pending',
                floatval($input['deposit_amount'] ?? 0.0),
                floatval($input['total_amount'] ?? 0.0)
            ]);
            
            $appointment_id = $db->lastInsertId();
            
            // Send email notification
            try {
                $email = new Email($db);
                $emailData = [
                    'customer_name' => $validation->sanitize($input['customer_name']),
                    'customer_phone' => $validation->sanitize($input['customer_phone']),
                    'customer_email' => $validation->sanitize($input['customer_email']),
                    'car_make' => $validation->sanitize($input['car_make']),
                    'car_model' => $validation->sanitize($input['car_model']),
                    'car_year' => intval($input['car_year']),
                    'service_type' => $validation->sanitize($input['service_type']),
                    'appointment_date' => $validation->sanitize($input['appointment_date']),
                    'appointment_time' => $validation->sanitize($input['appointment_time']),
                    'service_location' => $validation->sanitize($input['service_location'] ?? 'workshop'),
                    'county' => $validation->sanitize($input['county'] ?? ''),
                    'subcounty' => $validation->sanitize($input['subcounty'] ?? ''),
                    'address' => $validation->sanitize($input['address'] ?? ''),
                    'total_amount' => floatval($input['total_amount'] ?? 0.0),
                    'deposit_amount' => floatval($input['deposit_amount'] ?? 0.0),
                    'payment_status' => $input['payment_status'] ?? 'pending',
                    'notes' => $validation->sanitize($input['notes'] ?? '')
                ];
                $email->sendAppointmentNotification($emailData);
            } catch (Exception $e) {
                // Log email error but don't fail the appointment creation
                error_log('Email notification failed: ' . $e->getMessage());
            }
            
            $response->success(['appointment_id' => $appointment_id], 'Appointment booked successfully');
            
        } catch (Exception $e) {
            $response->error('Failed to create appointment: ' . $e->getMessage());
        }
        break;
        
    case 'PUT':
        // Update appointment status
        $user_data = $auth->protectRoute('admin'); // Only admin can update appointments
        
        if (!$id) {
            $response->error('Appointment ID is required', 400);
        }
        
        $required_fields = ['status'];
        $validation_result = $validation->validateRequired($input, $required_fields);
        
        if (!$validation_result['valid']) {
            $response->validationError($validation_result['errors']);
        }
        
        try {
            $stmt = $db->prepare("UPDATE appointments SET status = ?, notes = ? WHERE id = ?");
            $stmt->execute([
                $input['status'],
                $validation->sanitize($input['notes'] ?? ''),
                $id
            ]);
            
            $response->success(null, 'Appointment updated successfully');
            
        } catch (Exception $e) {
            $response->error('Failed to update appointment: ' . $e->getMessage());
        }
        break;
        
    case 'DELETE':
        // Cancel appointment (soft delete by changing status)
        $user_data = $auth->protectRoute('admin');
        
        if (!$id) {
            $response->error('Appointment ID is required', 400);
        }
        
        try {
            $stmt = $db->prepare("UPDATE appointments SET status = 'cancelled' WHERE id = ?");
            $stmt->execute([$id]);
            
            $response->success(null, 'Appointment cancelled successfully');
            
        } catch (Exception $e) {
            $response->error('Failed to cancel appointment: ' . $e->getMessage());
        }
        break;
        
    default:
        $response->error('Method not allowed', 405);
        break;
}