<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Include your DB connection (expects mysqli connection in $mysqli, $conn, $db, or $connection)
include('../../../dripend/includes/db.php');

// Normalize DB connection
if (isset($mysqli) && $mysqli instanceof mysqli) {
    $db = $mysqli;
} elseif (isset($conn) && $conn instanceof mysqli) {
    $db = $conn;
} elseif (isset($db) && $db instanceof mysqli) {
    // already $db
} elseif (isset($connection) && $connection instanceof mysqli) {
    $db = $connection;
} else {
    die("Database connection not found. Ensure includes/db.php defines a mysqli connection in \$mysqli, \$conn, \$db, or \$connection.");
}

// ----------------------
// Helper Functions
// ----------------------

// Generate next staff number in format HSP-YYYY-MM-XXXX
function generateStaffNumber($db) {
    $year = date('Y');
    $month = date('m');
    $prefix = "HSP-{$year}-{$month}-";

    $sql = "SELECT staff_no FROM staff WHERE staff_no LIKE '{$prefix}%' ORDER BY staff_id DESC LIMIT 1";
    $res = $db->query($sql);
    if ($res && $res->num_rows > 0) {
        $row = $res->fetch_assoc();
        if (preg_match('/(\d+)$/', $row['staff_no'], $m)) {
            $next = intval($m[1]) + 1;
        } else {
            $next = 1;
        }
    } else {
        $next = 1;
    }
    return $prefix . str_pad($next, 4, '0', STR_PAD_LEFT);
}

// Fetch lookup table options
function fetchLookup($db, $table, $idCol, $labelCol) {
    $options = [];
    $sql = "SELECT `$idCol` AS id, `$labelCol` AS name FROM `$table` ORDER BY `$labelCol` ASC";
    if ($res = $db->query($sql)) {
        while ($row = $res->fetch_assoc()) {
            $options[] = $row;
        }
    }
    return $options;
}

// ----------------------
// Load Lookup Tables
// ----------------------
$genders = fetchLookup($db, 'staff_gender', 'gender_id', 'gender_name');
$departments = fetchLookup($db, 'staff_department', 'staff_department_id', 'staff_department_name');
$positions = fetchLookup($db, 'staff_positions', 'position_id', 'position_name');
$qualifications = fetchLookup($db, 'staff_qualification', 'staff_qualification_id', 'staff_qualification_name');
$specializations = fetchLookup($db, 'staff_specializations', 'specialization_id', 'specialization_name');
$employment_types = fetchLookup($db, 'staff_employment_types', 'type_id', 'type_name');
$statuses = fetchLookup($db, 'staff_status', 'id', 'status_name');  // Correct
$roles = fetchLookup($db, 'staff_roles', 'role_id', 'role_name');
$is_doctor_options = fetchLookup($db, 'staff_is_doctor', 'is_doctor_id', 'is_doctor_name'); // Correct

// Generate staff number for this entry
$staff_no = generateStaffNumber($db);

// Initialize messages
$success = '';
$error = '';

// ----------------------
// Handle POST Submission
// ----------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize inputs
    $first_name = trim($_POST['first_name'] ?? '');
    $middle_name = trim($_POST['middle_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $gender_id = isset($_POST['gender_id']) && $_POST['gender_id'] !== '' ? intval($_POST['gender_id']) : null;
    $dob = $_POST['dob'] ?? null;
    $age = isset($_POST['age']) && $_POST['age'] !== '' ? intval($_POST['age']) : null;
    $national_id = trim($_POST['national_id'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $staff_department_id = isset($_POST['staff_department_id']) && $_POST['staff_department_id'] !== '' ? intval($_POST['staff_department_id']) : null;
    $position_id = isset($_POST['position_id']) && $_POST['position_id'] !== '' ? intval($_POST['position_id']) : null;
    $qualification_id = isset($_POST['qualification_id']) && $_POST['qualification_id'] !== '' ? intval($_POST['qualification_id']) : null;
    $specialization_id = isset($_POST['specialization_id']) && $_POST['specialization_id'] !== '' ? intval($_POST['specialization_id']) : null;
    $employment_type_id = isset($_POST['employment_type_id']) && $_POST['employment_type_id'] !== '' ? intval($_POST['employment_type_id']) : null;
    $date_joined = $_POST['date_joined'] ?? null;
    $status_id = isset($_POST['status_id']) && $_POST['status_id'] !== '' ? intval($_POST['status_id']) : null;
    $role_id = isset($_POST['role_id']) && $_POST['role_id'] !== '' ? intval($_POST['role_id']) : null;
    $is_doctor_id = isset($_POST['is_doctor_id']) && $_POST['is_doctor_id'] !== '' ? intval($_POST['is_doctor_id']) : null;
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $emergency_contact_name = trim($_POST['emergency_contact_name'] ?? '');
    $emergency_contact_phone = trim($_POST['emergency_contact_phone'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $photo_url = '';

    // Server-side validation
    if ($first_name === '' || $last_name === '') {
        $error = 'First name and last name are required.';
    } elseif ($phone === '') {
        $error = 'Phone number is required.';
    } elseif ($username !== '' && strlen($username) < 3) {
        $error = 'Username must be at least 3 characters.';
    }

    // Handle photo upload
    if (empty($error) && isset($_FILES['photo']) && $_FILES['photo']['error'] !== UPLOAD_ERR_NO_FILE) {
        if ($_FILES['photo']['error'] !== 0) {
            $error = 'Photo upload error code: ' . $_FILES['photo']['error'];
        } else {
            $uploadBase = __DIR__ . '/../../uploads/staff_photo/';
            if (!is_dir($uploadBase)) mkdir($uploadBase, 0755, true);
            $safeName = time() . '_' . preg_replace('/[^A-Za-z0-9_\-\.]/', '_', basename($_FILES['photo']['name']));
            $target = $uploadBase . $safeName;
            if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
                $photo_url = 'uploads/staff_photo/' . $safeName;
            } else {
                $error = 'Failed to move uploaded photo.';
            }
        }
    }

    // Hash password if provided
    $password_hash = '';
    if (empty($error) && $password !== '') {
        $password_hash = password_hash($password, PASSWORD_BCRYPT);
    }

    // Insert into staff table
    if (empty($error)) {
        $stmt = $db->prepare("
    INSERT INTO staff (
        staff_no, first_name, middle_name, last_name, gender_id, date_of_birth, age, national_id, phone,
        email, address, staff_department_id, position_id, qualification_id, specialization_id, employment_type_id,
        date_joined, status_id, role_id, is_doctor_id, username, password_hash, emergency_contact_name,
        emergency_contact_phone, photo_url, notes
    ) VALUES (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
    )
");

if ($stmt === false) {
    $error = 'Prepare failed: ' . $db->error;
} else {
    $stmt->bind_param(
    "sssssisisssiiiiiiiissssss",
    $staff_no,
    $first_name,
    $middle_name,
    $last_name,
    $gender_id,
    $dob,
    $age,
    $national_id,
    $phone,
    $email,
    $address,
    $staff_department_id,
    $position_id,
    $qualification_id,
    $specialization_id,
    $employment_type_id,
    $date_joined,
    $status_id,
    $role_id,
    $is_doctor_id,
    $username,
    $password_hash,
    $emergency_contact_name,
    $emergency_contact_phone,
    $photo_url,
    $notes
);


    if ($stmt->execute()) {
        $success = 'Staff member added successfully.';
        $staff_no = generateStaffNumber($db); // regenerate for next entry
    } else {
        $error = 'Insert failed: ' . $stmt->error;
    }

    $stmt->close();
}

    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Add New Staff | Hospital Management</title>
<style>
:root { --accent:#006400; --accent-dark:#004d00; --accent-gold:#ffd700; --bg:#f5f7fa; --card:#fff; --border:#d0d8e4; }
*{box-sizing:border-box}
body{font-family:Inter,Segoe UI,Arial,sans-serif;background:var(--bg);margin:0;padding:0;color:#222}
.page-wrapper{margin-left:0;padding:16px 28px 28px 28;}
.form-container{max-width:980px;margin:0 auto;background:var(--card);padding:28px;border-radius:10px;box-shadow:0 6px 24px rgba(0,0,0,0.06)}
.page-title{font-size:22px;font-weight:700;color:var(--accent-dark);text-align:center;margin-bottom:12px}
.btn-nav{background:var(--accent-gold);color:#004d00;margin-bottom:16px;display:inline-block;padding:8px 16px;border-radius:6px;text-decoration:none;font-weight:700;}
form{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px}
.form-group{display:flex;flex-direction:column}
label{font-weight:600;margin-bottom:6px;color:var(--accent-dark);font-size:14px}
input[type="text"],input[type="email"],input[type="date"],input[type="number"],input[type="password"],select,textarea,input[type="file"]{padding:10px;border:1px solid var(--border);border-radius:8px;font-size:14px}
input[readonly]{background:#f4f7fb}
textarea{min-height:70px;resize:none}
.section-header{grid-column:1/-1;background:var(--accent-gold);color:#004d00;padding:10px;border-radius:8px;font-weight:700;margin-top:12px}
.actions{grid-column:1/-1;display:flex;justify-content:flex-end;gap:10px;margin-top:6px}
.btn{padding:10px 18px;border-radius:8px;border:none;color:#fff;font-weight:700;cursor:pointer;text-decoration:none;text-align:center}
.btn-green{background:#2a9d8f}.btn-red{background:#e63946}.btn-blue{background:var(--accent)}
.alert-success{background:#d4edda;color:#155724;padding:10px;border-radius:6px;margin-bottom:12px}
.alert-error{background:#f8d7da;color:#721c24;padding:10px;border-radius:6px;margin-bottom:12px}
</style>
</head>
<body>
<div class="page-wrapper">

<a href="employee_management_dashboard.php" class="btn-nav">← Staff Dashboard</a>

<?php if ($success): ?>
<div class="alert-success"><?php echo htmlspecialchars($success); ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert-error"><?php echo htmlspecialchars($error); ?></div>
<?php endif; ?>

<div class="form-container">
<h1 class="page-title">Add New Staff</h1>

<form method="post" enctype="multipart/form-data" novalidate>

<!-- Photo -->
<div class="form-group">
<label for="photo">Upload Photo</label>
<input id="photo" type="file" name="photo" accept="image/*">
<div class="help">Optional. JPG or PNG. Max 2MB.</div>
</div>

<!-- Staff Number -->
<div class="form-group">
<label for="staff_no">Staff No</label>
<input id="staff_no" type="text" name="staff_no" value="<?php echo htmlspecialchars($staff_no); ?>" readonly>
</div>

<!-- Name Fields -->
<div class="form-group"><label for="first_name">First Name *</label><input id="first_name" name="first_name" type="text" required value="<?php echo htmlspecialchars($_POST['first_name'] ?? ''); ?>"></div>
<div class="form-group"><label for="middle_name">Middle Name</label><input id="middle_name" name="middle_name" type="text" value="<?php echo htmlspecialchars($_POST['middle_name'] ?? ''); ?>"></div>
<div class="form-group"><label for="last_name">Last Name *</label><input id="last_name" name="last_name" type="text" required value="<?php echo htmlspecialchars($_POST['last_name'] ?? ''); ?>"></div>

<!-- Gender, DOB, Age -->
<div class="form-group">
<label for="gender_id">Gender *</label>
<select id="gender_id" name="gender_id" required>
<option value="">Select</option>
<?php foreach ($genders as $g): ?>
<option value="<?php echo $g['id']; ?>" <?php echo (isset($_POST['gender_id']) && $_POST['gender_id']==$g['id'])?'selected':''; ?>><?php echo htmlspecialchars($g['name']); ?></option>
<?php endforeach; ?>
</select>
</div>

<div class="form-group"><label for="dob">Date of Birth *</label><input id="dob" name="dob" type="date" required value="<?php echo htmlspecialchars($_POST['dob'] ?? ''); ?>"></div>
<div class="form-group"><label for="age">Age</label><input id="age" name="age" type="number" readonly value="<?php echo htmlspecialchars($_POST['age'] ?? ''); ?>"></div>

<!-- Address -->
<div class="form-group"><label for="address">Address</label><input id="address" name="address" type="text" value="<?php echo htmlspecialchars($_POST['address'] ?? ''); ?>"></div>

<!-- Department -->
<div class="form-group">
<label for="staff_department_id">Department</label>
<select id="staff_department_id" name="staff_department_id">
<option value="">Select</option>
<?php foreach ($departments as $d): ?>
<option value="<?php echo $d['id']; ?>" <?php echo (isset($_POST['staff_department_id']) && $_POST['staff_department_id']==$d['id'])?'selected':''; ?>><?php echo htmlspecialchars($d['name']); ?></option>
<?php endforeach; ?>
</select>
</div>

<!-- Position -->
<div class="form-group">
<label for="position_id">Position</label>
<select id="position_id" name="position_id">
<option value="">Select</option>
<?php foreach ($positions as $p): ?>
<option value="<?php echo $p['id']; ?>" <?php echo (isset($_POST['position_id']) && $_POST['position_id']==$p['id'])?'selected':''; ?>><?php echo htmlspecialchars($p['name']); ?></option>
<?php endforeach; ?>
</select>
</div>

<!-- Qualification -->
<div class="form-group">
<label for="qualification_id">Qualification</label>
<select id="qualification_id" name="qualification_id">
<option value="">Select</option>
<?php foreach ($qualifications as $q): ?>
<option value="<?php echo $q['id']; ?>" <?php echo (isset($_POST['qualification_id']) && $_POST['qualification_id']==$q['id'])?'selected':''; ?>><?php echo htmlspecialchars($q['name']); ?></option>
<?php endforeach; ?>
</select>
</div>

<!-- Specialization -->
<div class="form-group">
<label for="specialization_id">Specialization</label>
<select id="specialization_id" name="specialization_id">
<option value="">Select</option>
<?php foreach ($specializations as $s): ?>
<option value="<?php echo $s['id']; ?>" <?php echo (isset($_POST['specialization_id']) && $_POST['specialization_id']==$s['id'])?'selected':''; ?>><?php echo htmlspecialchars($s['name']); ?></option>
<?php endforeach; ?>
</select>
</div>

<!-- Employment, Role, Status, Doctor -->
<div class="form-group">
<label for="employment_type_id">Employment Type</label>
<select id="employment_type_id" name="employment_type_id">
<option value="">Select</option>
<?php foreach ($employment_types as $e): ?>
<option value="<?php echo $e['id']; ?>" <?php echo (isset($_POST['employment_type_id']) && $_POST['employment_type_id']==$e['id'])?'selected':''; ?>><?php echo htmlspecialchars($e['name']); ?></option>
<?php endforeach; ?>
</select>
</div>

<div class="form-group">
<label for="role_id">Role</label>
<select id="role_id" name="role_id">
<option value="">Select</option>
<?php foreach ($roles as $r): ?>
<option value="<?php echo $r['id']; ?>" <?php echo (isset($_POST['role_id']) && $_POST['role_id']==$r['id'])?'selected':''; ?>><?php echo htmlspecialchars($r['name']); ?></option>
<?php endforeach; ?>
</select>
</div>

<div class="form-group">
<label for="status_id">Status</label>
<select id="status_id" name="status_id">
<option value="">Select</option>
<?php foreach ($statuses as $s): ?>
<option value="<?php echo $s['id']; ?>" <?php echo (isset($_POST['status_id']) && $_POST['status_id']==$s['id'])?'selected':''; ?>><?php echo htmlspecialchars($s['name']); ?></option>
<?php endforeach; ?>
</select>
</div>

<div class="form-group">
<label for="is_doctor_id">Is Doctor?</label>
<select id="is_doctor_id" name="is_doctor_id">
<option value="">Select</option>
<?php foreach ($is_doctor_options as $d): ?>
<option value="<?php echo $d['id']; ?>" <?php echo (isset($_POST['is_doctor_id']) && $_POST['is_doctor_id']==$d['id'])?'selected':''; ?>><?php echo htmlspecialchars($d['name']); ?></option>
<?php endforeach; ?>
</select>
</div>

<!-- Contact -->
<div class="form-group"><label for="phone">Phone *</label><input id="phone" name="phone" type="text" required value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>"></div>
<div class="form-group"><label for="email">Email</label><input id="email" name="email" type="email" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>"></div>

<!-- Emergency -->
<div class="section-header">Emergency Contact</div>
<div class="form-group"><label for="emergency_contact_name">Name</label><input id="emergency_contact_name" name="emergency_contact_name" type="text" value="<?php echo htmlspecialchars($_POST['emergency_contact_name'] ?? ''); ?>"></div>
<div class="form-group"><label for="emergency_contact_phone">Phone</label><input id="emergency_contact_phone" name="emergency_contact_phone" type="text" value="<?php echo htmlspecialchars($_POST['emergency_contact_phone'] ?? ''); ?>"></div>

<!-- System Access -->
<div class="section-header">System Access</div>
<div class="form-group"><label for="username">Username</label><input id="username" name="username" type="text" value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>"></div>
<div class="form-group"><label for="password">Password</label><input id="password" name="password" type="password"></div>

<!-- Actions -->
<div class="actions">
<button type="reset" class="btn btn-red">Reset</button>
<button type="submit" class="btn btn-green">Save Staff</button>
</div>
</form>
</div>
</div>

<script>
// Age calculation
const dob = document.getElementById('dob');
const age = document.getElementById('age');
if(dob && age){
dob.addEventListener('change', function(){
if(!this.value){age.value='';return;}
const d = new Date(this.value);
const t = new Date();
let years = t.getFullYear()-d.getFullYear();
if(t.getMonth()<d.getMonth()||(t.getMonth()===d.getMonth() && t.getDate()<d.getDate())) years--;
age.value=(years>=0)?years:'';
});
}
</script>
</body>
</html>
