<?php

session_start();

if (!isset($_SESSION['user_id'])) {

    echo '<p class="text-danger">Unauthorized</p>';

    exit;

}



require_once '../config.php';

$conn = getDBConnection();



$action = $_GET['action'] ?? ($_POST['action'] ?? '');

$id = intval($_GET['id'] ?? 0);



function safeHtml($str) {

    return htmlspecialchars($str ?? '', ENT_QUOTES, 'UTF-8');

}



// ── POST: reset teacher login ─────────────────────────────────────────────

if ($action === 'reset_teacher_login' && $_SERVER['REQUEST_METHOD'] === 'POST') {

    header('Content-Type: application/json');

    $staff_id = intval($_POST['staff_id'] ?? 0);

    if (!$staff_id) { echo json_encode(['success'=>false,'message'=>'Missing staff ID']); exit; }



    $sStmt = $conn->prepare("SELECT s.id, s.full_name, s.user_id FROM staff s WHERE s.id = ?");

    $sStmt->bind_param('i', $staff_id);

    $sStmt->execute();

    $staffRow = $sStmt->get_result()->fetch_assoc();

    $sStmt->close();



    if (!$staffRow) { echo json_encode(['success'=>false,'message'=>'Staff not found']); exit; }



    $temp_password = substr(str_shuffle('ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'), 0, 10);

    $hashed = password_hash($temp_password, PASSWORD_BCRYPT);



    if ($staffRow['user_id']) {

        // Update existing account

        $uUpd = $conn->prepare("SELECT username FROM users WHERE id = ?");

        $uUpd->bind_param('i', $staffRow['user_id']);

        $uUpd->execute();

        $uRow = $uUpd->get_result()->fetch_assoc();

        $uUpd->close();

        $username = $uRow['username'] ?? '';



        $pUpd = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");

        $pUpd->bind_param('si', $hashed, $staffRow['user_id']);

        $pUpd->execute();

        $pUpd->close();

        echo json_encode(['success'=>true,'username'=>$username,'password'=>$temp_password]);

    } else {

        // Create new user account for this teacher

        $nameParts = explode(' ', trim((string) $staffRow['full_name']));

        $base = strtolower(($nameParts[0][0] ?? '') . ($nameParts[count($nameParts)-1] ?? $nameParts[0]));

        $base = preg_replace('/[^a-z0-9]/', '', $base);

        $username = $base ?: 'teacher' . $staff_id;

        // Ensure uniqueness

        $uChk = $conn->prepare("SELECT id FROM users WHERE username = ?");

        $uChk->bind_param('s', $username);

        $uChk->execute();

        if ($uChk->get_result()->num_rows > 0) { $username .= $staff_id; }

        $uChk->close();



        $ins = $conn->prepare("INSERT INTO users (username, password, full_name, role, created_at) VALUES (?, ?, ?, 'tutor', NOW())");

        $ins->bind_param('sss', $username, $hashed, $staffRow['full_name']);

        $ins->execute();

        $new_uid = (int) $conn->insert_id;

        $ins->close();



        $link = $conn->prepare("UPDATE staff SET user_id = ? WHERE id = ?");

        $link->bind_param('ii', $new_uid, $staff_id);

        $link->execute();

        $link->close();



        echo json_encode(['success'=>true,'username'=>$username,'password'=>$temp_password]);

    }

    exit;

}



if ($action === 'edit' && $id > 0) {

    $result = $conn->query("SELECT * FROM staff WHERE id = $id");

    $staff = $result ? $result->fetch_assoc() : null;

    if (!$staff) {

        echo '<p class="text-danger">Staff not found</p>';

        exit;

    }

    ?>

    <input type="hidden" name="id" value="<?php echo $staff['id']; ?>">

    <!-- Build the same tabbed form with values filled -->

    <ul class="nav nav-tabs" id="editStaffTabs">

        <li class="nav-item"><div class="nav-link active" data-bs-toggle="tab" data-bs-target="#edit-particulars">Particulars</div></li>

        <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-professional">Professional</div></li>

        <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-bank">Bank & Official</div></li>

        <li class="nav-item"><div class="nav-link" data-bs-toggle="tab" data-bs-target="#edit-photo">Photo</div></li>

    </ul>

    <div class="tab-content mt-3">

        <!-- Particulars Tab -->

        <div class="tab-pane fade show active" id="edit-particulars">

            <div class="row">

                <div class="col-md-6 mb-3"><label>Staff ID</label><input type="text" class="form-control" name="staff_id" value="<?php echo safeHtml($staff['staff_id']); ?>" readonly></div>

                <div class="col-md-6 mb-3"><label>Full Name *</label><input type="text" class="form-control" name="full_name" value="<?php echo safeHtml($staff['full_name']); ?>" required></div>

                <div class="col-md-6 mb-3"><label>Reg. No</label><input type="text" class="form-control" name="reg_no" value="<?php echo safeHtml($staff['reg_no']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Date of Birth</label><input type="date" class="form-control" name="date_of_birth" value="<?php echo safeHtml($staff['date_of_birth']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Place of Birth</label><input type="text" class="form-control" name="place_of_birth" value="<?php echo safeHtml($staff['place_of_birth']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Age</label><input type="number" class="form-control" name="age" value="<?php echo $staff['age']; ?>"></div>

                <div class="col-md-4 mb-3"><label>Sex</label><select class="form-select" name="sex"><option value="">Select</option><option value="Male" <?php echo $staff['sex']=='Male'?'selected':''; ?>>Male</option><option value="Female" <?php echo $staff['sex']=='Female'?'selected':''; ?>>Female</option><option value="Other" <?php echo $staff['sex']=='Other'?'selected':''; ?>>Other</option></select></div>

                <div class="col-md-4 mb-3"><label>Nationality</label><input type="text" class="form-control" name="nationality" value="<?php echo safeHtml($staff['nationality']); ?>"></div>

                <div class="col-md-6 mb-3"><label>Residential Address</label><textarea class="form-control" name="residential_address"><?php echo safeHtml($staff['residential_address']); ?></textarea></div>

                <div class="col-md-6 mb-3"><label>Digital Address</label><input type="text" class="form-control" name="digital_address" value="<?php echo safeHtml($staff['digital_address']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Phone</label><input type="tel" class="form-control" name="phone" value="<?php echo safeHtml($staff['phone']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Tel No</label><input type="tel" class="form-control" name="tel_no" value="<?php echo safeHtml($staff['tel_no']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Email</label><input type="email" class="form-control" name="email" value="<?php echo safeHtml($staff['email']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Religion</label><input type="text" class="form-control" name="religious_denomination" value="<?php echo safeHtml($staff['religious_denomination']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Marital Status</label><select class="form-select" name="marital_status"><option value="">Select</option><option value="Single" <?php echo $staff['marital_status']=='Single'?'selected':''; ?>>Single</option><option value="Married" <?php echo $staff['marital_status']=='Married'?'selected':''; ?>>Married</option><option value="Divorced" <?php echo $staff['marital_status']=='Divorced'?'selected':''; ?>>Divorced</option><option value="Widowed" <?php echo $staff['marital_status']=='Widowed'?'selected':''; ?>>Widowed</option></select></div>

                <div class="col-md-4 mb-3"><label>Languages</label><input type="text" class="form-control" name="languages_spoken" value="<?php echo safeHtml($staff['languages_spoken']); ?>"></div>

                <div class="col-md-6 mb-3"><label>Next of Kin</label><input type="text" class="form-control" name="next_of_kin" value="<?php echo safeHtml($staff['next_of_kin']); ?>"></div>

                <div class="col-md-6 mb-3"><label>Next of Kin Phone</label><input type="tel" class="form-control" name="next_of_kin_phone" value="<?php echo safeHtml($staff['next_of_kin_phone']); ?>"></div>

                <div class="col-md-4 mb-3"><label>SSNIT</label><input type="text" class="form-control" name="ssnit_number" value="<?php echo safeHtml($staff['ssnit_number']); ?>"></div>

                <div class="col-md-4 mb-3"><label>TIN</label><input type="text" class="form-control" name="tin_number" value="<?php echo safeHtml($staff['tin_number']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Hometown</label><input type="text" class="form-control" name="hometown" value="<?php echo safeHtml($staff['hometown']); ?>"></div>

                <div class="col-md-4 mb-3"><label>District</label><input type="text" class="form-control" name="district" value="<?php echo safeHtml($staff['district']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Region</label><input type="text" class="form-control" name="region" value="<?php echo safeHtml($staff['region']); ?>"></div>

            </div>

        </div>

        <!-- Professional Tab -->

        <div class="tab-pane fade" id="edit-professional">

            <div class="row">

                <div class="col-md-6 mb-3"><label>Academic Qualification</label><textarea class="form-control" name="academic_qualification"><?php echo safeHtml($staff['academic_qualification']); ?></textarea></div>

                <div class="col-md-6 mb-3"><label>Professional Qualification</label><textarea class="form-control" name="professional_qualification"><?php echo safeHtml($staff['professional_qualification']); ?></textarea></div>

                <div class="col-md-4 mb-3"><label>Class Taught</label><input type="text" class="form-control" name="class_taught" value="<?php echo safeHtml($staff['class_taught']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Present Rank</label><input type="text" class="form-control" name="present_rank" value="<?php echo safeHtml($staff['present_rank']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Date Promoted</label><input type="date" class="form-control" name="date_promoted_to_present_rank" value="<?php echo safeHtml($staff['date_promoted_to_present_rank']); ?>"></div>

                <div class="col-md-4 mb-3"><label>1st Appointment</label><input type="date" class="form-control" name="date_of_first_appointment" value="<?php echo safeHtml($staff['date_of_first_appointment']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Year Certified</label><input type="text" class="form-control" name="year_of_certification" value="<?php echo safeHtml($staff['year_of_certification']); ?>"></div>

                <div class="col-md-12 mb-3"><label>Institutions Attended</label><textarea class="form-control" name="institutions_attended"><?php echo safeHtml($staff['institutions_attended']); ?></textarea></div>

                <div class="col-md-12 mb-3"><label>Teaching Experience</label><textarea class="form-control" name="teaching_experience"><?php echo safeHtml($staff['teaching_experience']); ?></textarea></div>

                <div class="col-md-12 mb-3"><label>Previous Schools</label><textarea class="form-control" name="previous_schools"><?php echo safeHtml($staff['previous_schools']); ?></textarea></div>

                <div class="col-md-4 mb-3"><label>Posted to Present Station</label><input type="date" class="form-control" name="date_posted_to_present_station" value="<?php echo safeHtml($staff['date_posted_to_present_station']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Retirement Date</label><input type="date" class="form-control" name="expected_retirement_date" value="<?php echo safeHtml($staff['expected_retirement_date']); ?>"></div>

            </div>

        </div>

        <!-- Bank & Official Tab -->

        <div class="tab-pane fade" id="edit-bank">

            <div class="row">

                <div class="col-md-6 mb-3"><label>Bank Name</label><input type="text" class="form-control" name="bank_name" value="<?php echo safeHtml($staff['bank_name']); ?>"></div>

                <div class="col-md-6 mb-3"><label>Bank Account</label><input type="text" class="form-control" name="bank_account" value="<?php echo safeHtml($staff['bank_account']); ?>"></div>

                <hr>

                <h6>Official Use</h6>

                <div class="col-md-4 mb-3"><label>Date of Employment</label><input type="date" class="form-control" name="date_of_employment" value="<?php echo safeHtml($staff['date_of_employment']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Salary</label><input type="number" step="0.01" class="form-control" name="salary" value="<?php echo $staff['salary']; ?>"></div>

                <div class="col-md-4 mb-3"><label>Class Assigned</label><input type="text" class="form-control" name="class_assigned" value="<?php echo safeHtml($staff['class_assigned']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Subject to Teach</label><input type="text" class="form-control" name="subject_to_teach" value="<?php echo safeHtml($staff['subject_to_teach']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Approved By</label><input type="text" class="form-control" name="approved_by" value="<?php echo safeHtml($staff['approved_by']); ?>"></div>

                <div class="col-md-4 mb-3"><label>Status</label><select class="form-select" name="status"><option value="active" <?php echo $staff['status']=='active'?'selected':''; ?>>Active</option><option value="inactive" <?php echo $staff['status']=='inactive'?'selected':''; ?>>Inactive</option></select></div>

            </div>

        </div>

        <!-- Photo Tab -->

        <div class="tab-pane fade" id="edit-photo">

            <div class="row">

                <div class="col-md-6">

                    <input type="hidden" name="existing_photo_path" value="<?php echo safeHtml($staff['photo_path']); ?>">

                    <?php if (!empty($staff['photo_path']) && file_exists('../'.$staff['photo_path'])): ?>

                        <p>Current Photo:</p>

                        <img src="./<?php echo $staff['photo_path']; ?>" style="max-width:200px;">

                        <div class="form-check">

                            <input class="form-check-input" type="checkbox" name="remove_photo" id="remove_photo">

                            <label class="form-check-label" for="remove_photo">Remove current photo</label>

                        </div>

                    <?php endif; ?>

                </div>

                <div class="col-md-6">

                    <label>Upload New Photo</label>

                    <input type="file" class="form-control" name="photo" accept="image/*">

                </div>

            </div>

        </div>

    </div>

    <?php

}

elseif ($action === 'view' && $id > 0) {

    $result = $conn->query("SELECT * FROM staff WHERE id = $id");

    $staff = $result ? $result->fetch_assoc() : null;

    if (!$staff) {

        echo '<p class="text-danger">Staff not found</p>';

        exit;

    }

    $photoField = !empty($staff['photo_path']) ? $staff['photo_path'] : ($staff['photo'] ?? '');

    $fieldMap = [

        'Staff ID' => $staff['staff_id'] ?? '',

        'Full Name' => $staff['full_name'] ?? '',

        'Reg No' => $staff['reg_no'] ?? '',

        'Gender' => $staff['gender'] ?? ($staff['sex'] ?? ''),

        'Sex' => $staff['sex'] ?? '',

        'Date of Birth' => $staff['date_of_birth'] ?? '',

        'Age' => $staff['age'] ?? '',

        'Place of Birth' => $staff['place_of_birth'] ?? '',

        'Nationality' => $staff['nationality'] ?? '',

        'Religion' => $staff['religion'] ?? ($staff['religious_denomination'] ?? ''),

        'Marital Status' => $staff['marital_status'] ?? '',

        'Phone' => $staff['phone'] ?? '',

        'Tel No' => $staff['tel_no'] ?? '',

        'Email' => $staff['email'] ?? '',

        'Address' => $staff['address'] ?? ($staff['residential_address'] ?? ''),

        'Residential Address' => $staff['residential_address'] ?? '',

        'Digital Address' => $staff['digital_address'] ?? '',

        'Role' => $staff['role'] ?? ($staff['present_rank'] ?? ''),

        'Department' => $staff['department'] ?? ($staff['class_taught'] ?? ''),

        'Academic Qualification' => $staff['academic_qualification'] ?? '',

        'Professional Qualification' => $staff['professional_qualification'] ?? '',

        'Class Taught' => $staff['class_taught'] ?? '',

        'Present Rank' => $staff['present_rank'] ?? '',

        'Date Promoted To Present Rank' => $staff['date_promoted_to_present_rank'] ?? '',

        'Date of First Appointment' => $staff['date_of_first_appointment'] ?? '',

        'Year of Certification' => $staff['year_of_certification'] ?? '',

        'Institutions Attended' => $staff['institutions_attended'] ?? '',

        'Teaching Experience' => $staff['teaching_experience'] ?? '',

        'Previous Schools' => $staff['previous_schools'] ?? '',

        'Date Joined' => $staff['date_joined'] ?? ($staff['date_of_employment'] ?? ''),

        'Date Posted To Present Station' => $staff['date_posted_to_present_station'] ?? '',

        'Expected Retirement Date' => $staff['expected_retirement_date'] ?? '',

        'Employment Type' => $staff['employment_type'] ?? '',

        'Bank Name' => $staff['bank_name'] ?? '',

        'Bank Account' => $staff['bank_account'] ?? '',

        'Bank Branch' => $staff['bank_branch'] ?? '',

        'SSNIT Number' => $staff['ssnit_number'] ?? '',

        'TIN Number' => $staff['tin_number'] ?? '',

        'District' => $staff['district'] ?? '',

        'Region' => $staff['region'] ?? '',

        'Hometown' => $staff['hometown'] ?? '',

        'Languages Spoken' => $staff['languages_spoken'] ?? '',

        'Next of Kin' => $staff['next_of_kin'] ?? ($staff['next_of_kin_name'] ?? ''),

        'Next of Kin Name' => $staff['next_of_kin_name'] ?? '',

        'Next of Kin Phone' => $staff['next_of_kin_phone'] ?? '',

        'Next of Kin Relation' => $staff['next_of_kin_relation'] ?? '',

        'Class Assigned' => $staff['class_assigned'] ?? '',

        'Subject to Teach' => $staff['subject_to_teach'] ?? '',

        'Date of Employment' => $staff['date_of_employment'] ?? '',

        'Salary' => $staff['salary'] ?? '',

        'Approved By' => $staff['approved_by'] ?? '',

        'Status' => $staff['status'] ?? '',

        'Created At' => $staff['created_at'] ?? '',

        'Updated At' => $staff['updated_at'] ?? ''

    ];

    ?>

    <div class="container-fluid">

        <?php if (!empty($photoField) && file_exists('../' . $photoField)): ?>

            <div class="text-center mb-3">

                <img src="./<?php echo safeHtml($photoField); ?>" style="max-height:150px; max-width:150px;" class="img-thumbnail">

            </div>

        <?php endif; ?>

        <table class="table table-bordered">

            <tbody>

                <?php foreach ($fieldMap as $label => $value): ?>

                    <tr>

                        <th style="width:35%;"><?php echo safeHtml($label); ?></th>

                        <td><?php echo safeHtml($value !== '' && $value !== null ? (string) $value : '-'); ?></td>

                    </tr>

                <?php endforeach; ?>

            </tbody>

        </table>

    </div>

    <?php

}

$conn->close();

?>

