<?php
/**
 * AUTO TESTER Recruitment System API
 * Comprehensive recruitment management for job applications and hiring
 */

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

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

// Load configuration
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../database.php';

class RecruitmentSystem {
    private $db;
    private $currentUser;
    
    public function __construct() {
        $this->db = Database::getInstance();
        $this->currentUser = $this->getCurrentUser();
    }
    
    /**
     * Get all job postings
     */
    public function getJobs() {
        $sql = "
            SELECT 
                j.*,
                (SELECT COUNT(*) FROM job_applications ja WHERE ja.job_id = j.id) as applications_count
            FROM jobs j
            WHERE j.is_active = TRUE 
            AND (j.expires_at IS NULL OR j.expires_at > CURDATE())
            ORDER BY j.is_featured DESC, j.created_at DESC
        ";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        
        return [
            'success' => true,
            'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)
        ];
    }
    
    /**
     * Get specific job details
     */
    public function getJob($id) {
        $stmt = $this->db->prepare("
            SELECT 
                j.*,
                (SELECT COUNT(*) FROM job_applications ja WHERE ja.job_id = j.id) as applications_count,
                (SELECT GROUP_CONCAT(skill_name ORDER BY skill_level DESC) 
                 FROM job_skills js WHERE js.job_id = j.id) as skills
            FROM jobs j
            WHERE j.id = ? AND j.is_active = TRUE
        ");
        $stmt->execute([$id]);
        $job = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($job) {
            // Increment view count
            $this->db->prepare("UPDATE jobs SET views_count = views_count + 1 WHERE id = ?")
                  ->execute([$id]);
            
            return [
                'success' => true,
                'data' => $job
            ];
        }
        
        return [
            'success' => false,
            'message' => 'Job not found'
        ];
    }
    
    /**
     * Apply for a job
     */
    public function applyJob() {
        // Validate required fields
        $required = ['job_id', 'full_name', 'email', 'phone'];
        foreach ($required as $field) {
            if (empty($_POST[$field])) {
                return [
                    'success' => false,
                    'message' => "Missing required field: {$field}"
                ];
            }
        }
        
        // Check for duplicate application
        $stmt = $this->db->prepare("
            SELECT COUNT(*) as count FROM job_applications 
            WHERE job_id = ? AND email = ? AND status != 'rejected'
        ");
        $stmt->execute([$_POST['job_id'], $_POST['email']]);
        $count = $stmt->fetch()['count'];
        
        if ($count > 0) {
            return [
                'success' => false,
                'message' => 'You have already applied for this job'
            ];
        }
        
        try {
            $this->db->beginTransaction();
            
            // Handle file upload
            $cvPath = $this->handleFileUpload('cv', 'cv');
            if (!$cvPath) {
                throw new Exception('CV upload failed');
            }
            
            $coverLetterPath = $this->handleFileUpload('cover_letter_file', 'cover_letters');
            
            // Insert application
            $stmt = $this->db->prepare("
                INSERT INTO job_applications (
                    job_id, full_name, email, phone, birth_date, address,
                    education_level, years_of_experience, current_salary, expected_salary,
                    notice_period_days, cv_file, cover_letter, portfolio_url,
                    linkedin_url, skills, languages, certifications
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $result = $stmt->execute([
                $_POST['job_id'],
                $_POST['full_name'],
                $_POST['email'],
                $_POST['phone'],
                $_POST['birth_date'] ?? null,
                $_POST['address'] ?? null,
                $_POST['education_level'] ?? null,
                $_POST['years_of_experience'] ?? 0,
                $_POST['current_salary'] ?? null,
                $_POST['expected_salary'] ?? null,
                $_POST['notice_period_days'] ?? 30,
                $cvPath,
                $coverLetterPath,
                $_POST['portfolio_url'] ?? null,
                $_POST['linkedin_url'] ?? null,
                $_POST['skills'] ?? null,
                $_POST['languages'] ?? null,
                $_POST['certifications'] ?? null
            ]);
            
            if (!$result) {
                throw new Exception('Failed to insert application');
            }
            
            $applicationId = $this->db->lastInsertId();
            
            // Send notification
            $this->sendApplicationNotification($applicationId);
            
            $this->db->commit();
            
            return [
                'success' => true,
                'message' => 'Application submitted successfully',
                'data' => [
                    'application_id' => $applicationId,
                    'application_number' => $this->getApplicationNumber($applicationId)
                ]
            ];
            
        } catch (Exception $e) {
            $this->db->rollBack();
            error_log("Job application error: " . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Failed to submit application'
            ];
        }
    }
    
    /**
     * Get job applications
     */
    public function getJobApplications($status = null) {
        $sql = "
            SELECT 
                ja.*,
                j.title_ar as job_title,
                j.department,
                j.location
            FROM job_applications ja
            JOIN jobs j ON ja.job_id = j.id
        ";
        
        $params = [];
        if ($status) {
            $sql .= " WHERE ja.status = ?";
            $params[] = $status;
        }
        
        $sql .= " ORDER BY ja.created_at DESC";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        
        return [
            'success' => true,
            'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)
        ];
    }
    
    /**
     * Get application details
     */
    public function getApplicationDetails($id) {
        $stmt = $this->db->prepare("
            SELECT 
                ja.*,
                j.title_ar as job_title,
                j.title as job_title_en,
                j.department,
                j.location,
                j.employment_type
            FROM job_applications ja
            JOIN jobs j ON ja.job_id = j.id
            WHERE ja.id = ?
        ");
        $stmt->execute([$id]);
        $application = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($application) {
            return [
                'success' => true,
                'data' => $application
            ];
        }
        
        return [
            'success' => false,
            'message' => 'Application not found'
        ];
    }
    
    /**
     * Update application status
     */
    public function updateApplicationStatus() {
        $applicationId = $_POST['application_id'] ?? '';
        $status = $_POST['status'] ?? '';
        $notes = $_POST['notes'] ?? '';
        $rejectionReason = $_POST['rejection_reason'] ?? '';
        
        if (!$applicationId || !$status) {
            return [
                'success' => false,
                'message' => 'Missing required fields'
            ];
        }
        
        try {
            $this->db->beginTransaction();
            
            // Update application
            $stmt = $this->db->prepare("
                UPDATE job_applications 
                SET status = ?, reviewed_by = ?, review_notes = ?, rejection_reason = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$status, $this->currentUser['id'], $notes, $rejectionReason, $applicationId]);
            
            // Send notification
            $this->sendStatusNotification($applicationId, $status);
            
            $this->db->commit();
            
            return [
                'success' => true,
                'message' => 'Application status updated successfully'
            ];
            
        } catch (Exception $e) {
            $this->db->rollBack();
            error_log("Status update error: " . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Failed to update status'
            ];
        }
    }
    
    /**
     * Schedule interview
     */
    public function scheduleInterview() {
        $applicationId = $_POST['application_id'] ?? '';
        $date = $_POST['interview_date'] ?? '';
        $time = $_POST['interview_time'] ?? '';
        $type = $_POST['interview_type'] ?? '';
        $meetingLink = $_POST['meeting_link'] ?? '';
        $location = $_POST['location'] ?? '';
        $duration = $_POST['duration'] ?? 60;
        
        if (!$applicationId || !$date || !$time || !$type) {
            return [
                'success' => false,
                'message' => 'Missing required fields'
            ];
        }
        
        try {
            $this->db->beginTransaction();
            
            $interviewDateTime = $date . ' ' . $time;
            
            // Insert interview
            $stmt = $this->db->prepare("
                INSERT INTO interviews (
                    application_id, interviewer_id, interview_date, interview_type,
                    meeting_link, location, duration_minutes
                ) VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            
            $result = $stmt->execute([
                $applicationId,
                $this->currentUser['id'],
                $interviewDateTime,
                $type,
                $meetingLink,
                $location,
                $duration
            ]);
            
            if (!$result) {
                throw new Exception('Failed to schedule interview');
            }
            
            // Update application status
            $stmt = $this->db->prepare("
                UPDATE job_applications 
                SET status = 'interview', interview_date = ?, interview_type = ?
                WHERE id = ?
            ");
            $stmt->execute([$interviewDateTime, $type, $applicationId]);
            
            // Send interview notification
            $this->sendInterviewNotification($applicationId, $interviewDateTime, $type, $meetingLink, $location);
            
            $this->db->commit();
            
            return [
                'success' => true,
                'message' => 'Interview scheduled successfully'
            ];
            
        } catch (Exception $e) {
            $this->db->rollBack();
            error_log("Interview scheduling error: " . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Failed to schedule interview'
            ];
        }
    }
    
    /**
     * Get interviews
     */
    public function getInterviews() {
        $stmt = $this->db->prepare("
            SELECT 
                i.*,
                ja.full_name as candidate_name,
                ja.email as candidate_email,
                j.title_ar as job_title,
                u.full_name as interviewer_name
            FROM interviews i
            JOIN job_applications ja ON i.application_id = ja.id
            JOIN jobs j ON ja.job_id = j.id
            LEFT JOIN users u ON i.interviewer_id = u.id
            ORDER BY i.interview_date DESC
        ");
        $stmt->execute();
        
        return [
            'success' => true,
            'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)
        ];
    }
    
    /**
     * Submit evaluation
     */
    public function submitEvaluation() {
        $applicationId = $_POST['application_id'] ?? '';
        $criteria = $_POST['criteria'] ?? [];
        $notes = $_POST['notes'] ?? '';
        
        if (!$applicationId || empty($criteria)) {
            return [
                'success' => false,
                'message' => 'Missing required fields'
            ];
        }
        
        try {
            $this->db->beginTransaction();
            
            foreach ($criteria as $criterion) {
                $stmt = $this->db->prepare("
                    INSERT INTO applicant_evaluations 
                    (application_id, evaluator_id, criteria_name, score, notes)
                    VALUES (?, ?, ?, ?, ?)
                    ON DUPLICATE KEY UPDATE
                    score = VALUES(score), notes = VALUES(notes), evaluated_at = NOW()
                ");
                
                $stmt->execute([
                    $applicationId,
                    $this->currentUser['id'],
                    $criterion['name'],
                    $criterion['score'],
                    $criterion['notes'] ?? ''
                ]);
            }
            
            $this->db->commit();
            
            return [
                'success' => true,
                'message' => 'Evaluation submitted successfully'
            ];
            
        } catch (Exception $e) {
            $this->db->rollBack();
            error_log("Evaluation submission error: " . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Failed to submit evaluation'
            ];
        }
    }
    
    /**
     * Get evaluations
     */
    public function getEvaluations() {
        $stmt = $this->db->prepare("
            SELECT 
                ae.*,
                ja.full_name as candidate_name,
                j.title_ar as job_title,
                u.full_name as evaluator_name
            FROM applicant_evaluations ae
            JOIN job_applications ja ON ae.application_id = ja.id
            JOIN jobs j ON ja.job_id = j.id
            LEFT JOIN users u ON ae.evaluator_id = u.id
            ORDER BY ae.evaluated_at DESC
        ");
        $stmt->execute();
        
        return [
            'success' => true,
            'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)
        ];
    }
    
    /**
     * Get recruitment dashboard statistics
     */
    public function getRecruitmentDashboard() {
        $stats = [];
        
        // Total applications
        $stmt = $this->db->prepare("SELECT COUNT(*) as count FROM job_applications");
        $stmt->execute();
        $stats['total_applications'] = $stmt->fetch()['count'];
        
        // Hired candidates
        $stmt = $this->db->prepare("SELECT COUNT(*) as count FROM job_applications WHERE status = 'hired'");
        $stmt->execute();
        $stats['hired_candidates'] = $stmt->fetch()['count'];
        
        // Interviews scheduled
        $stmt = $this->db->prepare("SELECT COUNT(*) as count FROM interviews WHERE status = 'scheduled'");
        $stmt->execute();
        $stats['interviews_scheduled'] = $stmt->fetch()['count'];
        
        // Active jobs
        $stmt = $this->db->prepare("SELECT COUNT(*) as count FROM jobs WHERE is_active = TRUE");
        $stmt->execute();
        $stats['active_jobs'] = $stmt->fetch()['count'];
        
        return [
            'success' => true,
            'data' => $stats
        ];
    }
    
    /**
     * Get notifications
     */
    public function getNotifications() {
        $stmt = $this->db->prepare("
            SELECT 
                rn.*,
                ja.full_name as candidate_name
            FROM recruitment_notifications rn
            LEFT JOIN job_applications ja ON rn.application_id = ja.id
            ORDER BY rn.sent_at DESC
            LIMIT 50
        ");
        $stmt->execute();
        
        return [
            'success' => true,
            'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)
        ];
    }
    
    // Private helper methods
    
    private function getCurrentUser() {
        // This would typically get the current user from session or token
        // For now, return a default admin user
        return [
            'id' => 1,
            'name' => 'System Admin',
            'role' => 'admin'
        ];
    }
    
    private function handleFileUpload($fieldName, $folder) {
        if (!isset($_FILES[$fieldName]) || $_FILES[$fieldName]['error'] !== 0) {
            return null;
        }
        
        $file = $_FILES[$fieldName];
        $uploadDir = __DIR__ . '/../../uploads/recruitment/' . $folder . '/';
        
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        
        $fileName = uniqid() . '_' . basename($file['name']);
        $filePath = $uploadDir . $fileName;
        
        if (move_uploaded_file($file['tmp_name'], $filePath)) {
            return '/uploads/recruitment/' . $folder . '/' . $fileName;
        }
        
        return null;
    }
    
    private function getApplicationNumber($applicationId) {
        $stmt = $this->db->prepare("SELECT application_number FROM job_applications WHERE id = ?");
        $stmt->execute([$applicationId]);
        $result = $stmt->fetch();
        return $result['application_number'] ?? '';
    }
    
    private function sendApplicationNotification($applicationId) {
        $stmt = $this->db->prepare("
            SELECT ja.full_name, ja.email, j.title_ar as job_title 
            FROM job_applications ja
            JOIN jobs j ON ja.job_id = j.id
            WHERE ja.id = ?
        ");
        $stmt->execute([$applicationId]);
        $app = $stmt->fetch();
        
        if ($app) {
            $stmt = $this->db->prepare("
                INSERT INTO recruitment_notifications 
                (application_id, applicant_email, type, title, message)
                VALUES (?, ?, 'application_received', 'Application Received', ?)
            ");
            
            $message = "Thank you {$app['full_name']} for applying to {$app['job_title']}. We will review your application and contact you soon.";
            $stmt->execute([$applicationId, $app['email'], $message]);
        }
    }
    
    private function sendStatusNotification($applicationId, $status) {
        $stmt = $this->db->prepare("
            SELECT ja.full_name, ja.email, j.title_ar as job_title 
            FROM job_applications ja
            JOIN jobs j ON ja.job_id = j.id
            WHERE ja.id = ?
        ");
        $stmt->execute([$applicationId]);
        $app = $stmt->fetch();
        
        if ($app) {
            $messages = [
                'reviewing' => 'Your application is being reviewed',
                'shortlisted' => 'Congratulations! You have been shortlisted',
                'interview' => 'An interview has been scheduled',
                'accepted' => 'Congratulations! You have been accepted',
                'rejected' => 'Unfortunately, your application was not successful'
            ];
            
            $message = $messages[$status] ?? 'Your application status has been updated';
            
            $stmt = $this->db->prepare("
                INSERT INTO recruitment_notifications 
                (application_id, applicant_email, type, title, message)
                VALUES (?, ?, 'status_update', 'Application Status Update', ?)
            ");
            
            $stmt->execute([$applicationId, $app['email'], $message]);
        }
    }
    
    private function sendInterviewNotification($applicationId, $dateTime, $type, $meetingLink, $location) {
        $stmt = $this->db->prepare("
            SELECT ja.full_name, ja.email, j.title_ar as job_title 
            FROM job_applications ja
            JOIN jobs j ON ja.job_id = j.id
            WHERE ja.id = ?
        ");
        $stmt->execute([$applicationId]);
        $app = $stmt->fetch();
        
        if ($app) {
            $details = '';
            if ($type === 'online' && $meetingLink) {
                $details = "Meeting link: {$meetingLink}";
            } elseif ($type === 'onsite' && $location) {
                $details = "Location: {$location}";
            }
            
            $message = "Interview scheduled for {$dateTime}. {$details}";
            
            $stmt = $this->db->prepare("
                INSERT INTO recruitment_notifications 
                (application_id, applicant_email, type, title, message)
                VALUES (?, ?, 'interview_scheduled', 'Interview Scheduled', ?)
            ");
            
            $stmt->execute([$applicationId, $app['email'], $message]);
        }
    }
}

// Handle API requests
try {
    $recruitment = new RecruitmentSystem();
    $action = $_GET['action'] ?? '';
    
    switch ($action) {
        case 'get-jobs':
            echo json_encode($recruitment->getJobs(), JSON_UNESCAPED_UNICODE);
            break;
            
        case 'get-job':
            $id = $_GET['id'] ?? '';
            echo json_encode($recruitment->getJob($id), JSON_UNESCAPED_UNICODE);
            break;
            
        case 'apply-job':
            echo json_encode($recruitment->applyJob(), JSON_UNESCAPED_UNICODE);
            break;
            
        case 'get_job_applications':
            $status = $_GET['status'] ?? null;
            echo json_encode($recruitment->getJobApplications($status), JSON_UNESCAPED_UNICODE);
            break;
            
        case 'get_application_details':
            $id = $_GET['id'] ?? '';
            echo json_encode($recruitment->getApplicationDetails($id), JSON_UNESCAPED_UNICODE);
            break;
            
        case 'update_application_status':
            echo json_encode($recruitment->updateApplicationStatus(), JSON_UNESCAPED_UNICODE);
            break;
            
        case 'schedule_interview':
            echo json_encode($recruitment->scheduleInterview(), JSON_UNESCAPED_UNICODE);
            break;
            
        case 'get_interviews':
            echo json_encode($recruitment->getInterviews(), JSON_UNESCAPED_UNICODE);
            break;
            
        case 'submit_evaluation':
            echo json_encode($recruitment->submitEvaluation(), JSON_UNESCAPED_UNICODE);
            break;
            
        case 'get_evaluations':
            echo json_encode($recruitment->getEvaluations(), JSON_UNESCAPED_UNICODE);
            break;
            
        case 'get_recruitment_dashboard':
            echo json_encode($recruitment->getRecruitmentDashboard(), JSON_UNESCAPED_UNICODE);
            break;
            
        case 'get_notifications':
            echo json_encode($recruitment->getNotifications(), JSON_UNESCAPED_UNICODE);
            break;
            
        default:
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'message' => 'Invalid action'
            ]);
    }
    
} catch (Exception $e) {
    error_log("Recruitment API Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal server error'
    ]);
}
?>
