<?php
require_once APP_PATH . '/Core/BaseController.php';
require_once APP_PATH . '/Core/CSRF.php';

class ProfileController extends BaseController {

    public function show(): void {
        $userId = Auth::id();
        $db     = Database::getInstance();
        $user   = $db->prepare("SELECT * FROM users WHERE id = ?")->execute([$userId]) ?
                  $db->query("SELECT * FROM users WHERE id = {$userId}")->fetch() : null;

        $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();

        $profile = null;
        $role    = Auth::role();
        if ($role === 'student') {
            $stmt2 = $db->prepare("SELECT sp.*, c.name AS country_name, r.name AS region_name FROM student_profiles sp LEFT JOIN countries c ON c.id = sp.country_id LEFT JOIN regions r ON r.id = sp.region_id WHERE sp.user_id = ?");
            $stmt2->execute([$userId]);
            $profile = $stmt2->fetch();

            $stmt3 = $db->prepare("SELECT * FROM wassce_results WHERE user_id = ? ORDER BY subject");
            $stmt3->execute([$userId]);
            $wassce = $stmt3->fetchAll();
        }

        $this->view('profile.show', [
            'title'   => 'My Profile — BOAFO',
            'user'    => $user,
            'profile' => $profile ?? [],
            'wassce'  => $wassce ?? [],
        ]);
    }

    public function edit(): void {
        $userId = Auth::id();
        $db     = Database::getInstance();

        $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();

        $role = Auth::role();
        $profile = [];
        if ($role === 'student') {
            $stmt2 = $db->prepare("SELECT * FROM student_profiles WHERE user_id = ?");
            $stmt2->execute([$userId]);
            $profile = $stmt2->fetch() ?: [];
        } elseif ($role === 'mentor') {
            $stmt2 = $db->prepare("SELECT * FROM mentor_profiles WHERE user_id = ?");
            $stmt2->execute([$userId]);
            $profile = $stmt2->fetch() ?: [];
        } elseif ($role === 'tutor') {
            $stmt2 = $db->prepare("SELECT * FROM tutor_profiles WHERE user_id = ?");
            $stmt2->execute([$userId]);
            $profile = $stmt2->fetch() ?: [];
        }

        $countries    = $db->query("SELECT * FROM countries ORDER BY name")->fetchAll();
        $regions      = $db->query("SELECT * FROM regions WHERE country_id = 1 ORDER BY name")->fetchAll();
        $universities = $db->query("SELECT id, name FROM universities WHERE status='active' ORDER BY name")->fetchAll();

        $availability = [];
        if ($role === 'mentor' || $role === 'tutor') {
            $stmt3 = $db->prepare("SELECT * FROM user_availability WHERE user_id = ?");
            $stmt3->execute([$userId]);
            $availability = $stmt3->fetchAll();
        }

        $this->view('profile.edit', [
            'title'        => 'Edit Profile — BOAFO',
            'user'         => $user,
            'profile'      => $profile,
            'countries'    => $countries,
            'regions'      => $regions,
            'universities' => $universities,
            'availability' => $availability,
            'errors'       => $this->getFlash('errors') ?? [],
            'success'      => $this->getFlash('success'),
        ]);
    }

    public function update(): void {
        CSRF::check();

        $userId = Auth::id();
        $db     = Database::getInstance();
        $role   = Auth::role();

        // Update core user info
        $firstName = $this->sanitize($this->input('first_name', ''));
        $lastName  = $this->sanitize($this->input('last_name', ''));
        $phone     = $this->sanitize($this->input('phone', ''));

        $db->prepare("UPDATE users SET first_name = ?, last_name = ?, phone = ? WHERE id = ?")
           ->execute([$firstName, $lastName, $phone, $userId]);

        // Update role profile
        if ($role === 'student') {
            $data = [
                'date_of_birth'      => $this->input('date_of_birth') ?: null,
                'gender'             => $this->input('gender') ?: null,
                'country_id'         => $this->input('country_id') ?: null,
                'region_id'          => $this->input('region_id') ?: null,
                'city'               => $this->sanitize($this->input('city', '')),
                'shs_school'         => $this->sanitize($this->input('shs_school', '')),
                'shs_program'        => $this->input('shs_program') ?: null,
                'graduation_year'    => $this->input('graduation_year') ?: null,
                'intended_program'   => $this->sanitize($this->input('intended_program', '')),
                'preferred_university'=>$this->sanitize($this->input('preferred_university', '')),
                'career_interests'   => $this->sanitize($this->input('career_interests', '')),
                'academic_strengths' => $this->sanitize($this->input('academic_strengths', '')),
                'financial_need'     => $this->input('financial_need', 'moderate'),
                'bio'                => $this->sanitize($this->input('bio', '')),
            ];
            $sets = implode(', ', array_map(fn($k) => "{$k} = ?", array_keys($data)));
            $db->prepare("UPDATE student_profiles SET {$sets} WHERE user_id = ?")
               ->execute([...array_values($data), $userId]);

            // Mark profile completed if key fields filled
            $completed = !empty($data['gender']) && !empty($data['intended_program']) && !empty($data['shs_program']);
            $db->prepare("UPDATE student_profiles SET profile_completed = ? WHERE user_id = ?")
               ->execute([(int)$completed, $userId]);

        } elseif ($role === 'mentor') {
            $data = [
                'university_id'  => $this->input('university_id') ?: null,
                'program'        => $this->sanitize($this->input('program', '')),
                'faculty'        => $this->sanitize($this->input('faculty', '')),
                'year_level'     => $this->input('year_level') ?: null,
                'expertise_areas'=> $this->sanitize($this->input('expertise_areas', '')),
                'career_goals'   => $this->sanitize($this->input('career_goals', '')),
                'bio'            => $this->sanitize($this->input('bio', '')),
                'linkedin_url'   => $this->sanitize($this->input('linkedin_url', '')),
                'max_mentees'    => (int)$this->input('max_mentees', 5),
                'country_id'     => $this->input('country_id') ?: null,
            ];
            $sets = implode(', ', array_map(fn($k) => "{$k} = ?", array_keys($data)));
            $db->prepare("UPDATE mentor_profiles SET {$sets} WHERE user_id = ?")
               ->execute([...array_values($data), $userId]);
        } elseif ($role === 'tutor') {
            $data = [
                'specializations' => $this->sanitize($this->input('specializations', '')),
                'subjects'        => $this->sanitize($this->input('subjects', '')),
                'qualification'   => $this->sanitize($this->input('qualification', '')),
                'institution'     => $this->sanitize($this->input('institution', '')),
                'bio'             => $this->sanitize($this->input('bio', '')),
                'hourly_rate'     => $this->input('hourly_rate') ?: null,
            ];
            $sets = implode(', ', array_map(fn($k) => "{$k} = ?", array_keys($data)));
            $db->prepare("UPDATE tutor_profiles SET {$sets} WHERE user_id = ?")
               ->execute([...array_values($data), $userId]);
        }

        // Update Availability
        if ($role === 'mentor' || $role === 'tutor') {
            $availInput = $_POST['availability'] ?? [];
            if (is_array($availInput)) {
                $db->prepare("DELETE FROM user_availability WHERE user_id = ?")->execute([$userId]);
                $stmtAvail = $db->prepare("INSERT INTO user_availability (user_id, day_of_week, start_time, end_time) VALUES (?, ?, ?, ?)");
                foreach ($availInput as $day => $times) {
                    $starts = $times['start'] ?? [];
                    $ends = $times['end'] ?? [];
                    if (is_array($starts) && is_array($ends)) {
                        foreach ($starts as $index => $startTime) {
                            $endTime = $ends[$index] ?? '';
                            if (!empty($startTime) && !empty($endTime)) {
                                $stmtAvail->execute([$userId, (int)$day, $startTime, $endTime]);
                            }
                        }
                    }
                }
            }
        }


        // Update session name
        $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $updated = $stmt->fetch();
        $_SESSION['user']['name']   = $updated['first_name'] . ' ' . $updated['last_name'];
        $_SESSION['user']['avatar'] = $updated['avatar'];

        $this->flash('success', 'Profile updated successfully!');
        $this->redirect(APP_URL . '/profile/edit');
    }

    public function uploadAvatar(): void {
        CSRF::check();
        if (empty($_FILES['avatar'])) {
            $this->json(['success'=>false,'message'=>'No file uploaded.']);
        }

        $filename = uploadFile($_FILES['avatar'], 'avatars', ALLOWED_IMAGE_TYPES);
        if (!$filename) {
            $this->json(['success'=>false,'message'=>'Invalid file. Upload JPG/PNG under 5MB.']);
        }

        $db = Database::getInstance();
        $db->prepare("UPDATE users SET avatar = ? WHERE id = ?")->execute([$filename, Auth::id()]);
        $_SESSION['user']['avatar'] = $filename;

        $this->json(['success'=>true,'avatar_url'=>UPLOAD_URL . '/avatars/' . $filename]);
    }

    public function wassce(): void {
        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT * FROM wassce_results WHERE user_id = ? ORDER BY subject");
        $stmt->execute([Auth::id()]);
        $wassce = $stmt->fetchAll();

        $this->view('profile.wassce', [
            'title'  => 'WASSCE Results — BOAFO',
            'wassce' => $wassce,
            'grades' => array_keys(WASSCE_GRADES),
            'success'=> $this->getFlash('success'),
            'error'  => $this->getFlash('error'),
        ]);
    }

    public function saveWassce(): void {
        CSRF::check();

        $subjects = $_POST['subjects'] ?? [];
        $grades   = $_POST['grades']   ?? [];
        $year     = (int)$this->input('year', date('Y'));

        if (empty($subjects)) {
            $this->flash('error', 'Please add at least one subject.');
            $this->redirect(APP_URL . '/profile/wassce');
        }

        $db = Database::getInstance();
        $db->prepare("DELETE FROM wassce_results WHERE user_id = ?")->execute([Auth::id()]);

        $stmt = $db->prepare("INSERT INTO wassce_results (user_id, subject, grade, year) VALUES (?, ?, ?, ?)");
        foreach ($subjects as $i => $subject) {
            if (!empty($subject) && !empty($grades[$i])) {
                $stmt->execute([Auth::id(), $this->sanitize($subject), $grades[$i], $year]);
            }
        }

        $this->flash('success', 'WASSCE results saved successfully!');
        $this->redirect(APP_URL . '/profile/wassce');
    }
}
