<?php
session_start();
include('includes/config.php');
error_reporting(0);
date_default_timezone_set('Asia/Kolkata');

// Allow only admin or staff to access (admin can edit any staff, staff only own profile)
if (!isset($_SESSION['alogin']) && !isset($_SESSION['staff_login'])) {
  header('location:index.php');
  exit;
}

// Determine staff ID to edit: admin can use ?sid=... else staff edits own
$sid = isset($_GET['sid']) ? $_GET['sid'] : (isset($_SESSION['staffid']) ? $_SESSION['staffid'] : null);

if (!$sid) {
  echo "<script>alert('Invalid staff ID'); window.location.href='index.php';</script>";
  exit;
}

// Fetch staff details with joins
$sql = "SELECT st.*, 
               d.department_name, 
               des.designation_name, 
               g.gender_name, 
               deg.degree_name
        FROM tblstaff st
        LEFT JOIN tbldepartment d ON st.department_id=d.department_id
        LEFT JOIN tblstaffdesignation des ON st.designation_id=des.designation_id
        LEFT JOIN tblgender g ON st.gender_id=g.gender_id
        LEFT JOIN tbldegree deg ON st.degree_id=deg.degree_id
        WHERE st.StaffId = :sid";

$query = $dbh->prepare($sql);
$query->bindParam(':sid', $sid, PDO::PARAM_STR);
$query->execute();
$result = $query->fetch(PDO::FETCH_OBJ);

if (!$result) {
  echo "<script>alert('Staff not found'); window.location.href='reg-staffs.php';</script>";
  exit;
}

// Handle form submission
if (isset($_POST['update'])) {
  $fname = $_POST['fullname'];
  $mobileno = $_POST['mobileno'];
  $address = $_POST['address'];
  $qualification = $_POST['qualification'];
  $joiningDate = $_POST['joiningdate'];

  $uploadDirId = "uploads/idproofs/";
  $uploadDirPhoto = "uploads/photos/";

  if (!file_exists($uploadDirId))
    mkdir($uploadDirId, 0755, true);
  if (!file_exists($uploadDirPhoto))
    mkdir($uploadDirPhoto, 0755, true);

  $idProofPath = '';
  $photoPath = '';

  if (!empty($_FILES['idproof']['name'])) {
    $idProofName = time() . "_" . basename($_FILES['idproof']['name']);
    $idProofPath = $uploadDirId . $idProofName;
    move_uploaded_file($_FILES['idproof']['tmp_name'], $idProofPath);
  }

  if (!empty($_FILES['photo']['name'])) {
    $photoName = time() . "_" . basename($_FILES['photo']['name']);
    $photoPath = $uploadDirPhoto . $photoName;
    move_uploaded_file($_FILES['photo']['tmp_name'], $photoPath);
  }
  $updatedate = date('Y-m-d H:i:s');
  $sqlUpdate = "UPDATE tblstaff SET FullName=:fname, MobileNumber=:mobileno, Address=:address, Qualification=:qualification, JoiningDate=:joiningDate";
  if ($idProofPath != '')
    $sqlUpdate .= ", IDProof=:idproof";
  if ($photoPath != '')
    $sqlUpdate .= ", Photo=:photo";
  $sqlUpdate .= ", UpdationDate=:updatedate WHERE StaffId=:sid";

  $queryUpdate = $dbh->prepare($sqlUpdate);
  $queryUpdate->bindParam(':fname', $fname);
  $queryUpdate->bindParam(':mobileno', $mobileno);
  $queryUpdate->bindParam(':address', $address);
  $queryUpdate->bindParam(':qualification', $qualification);
  $queryUpdate->bindParam(':joiningDate', $joiningDate);
  $queryUpdate->bindParam(':sid', $sid);
  $queryUpdate->bindParam(':updatedate', $updatedate);

  if ($idProofPath != '')
    $queryUpdate->bindParam(':idproof', $idProofPath);
  if ($photoPath != '')
    $queryUpdate->bindParam(':photo', $photoPath);

  if ($queryUpdate->execute()) {
    echo "<script>alert('Staff profile updated successfully'); window.location.href='reg-staffs.php';</script>";
    exit;
  } else {
    echo "<script>alert('Error updating profile');</script>";
  }
}

// Define default photo fallback
$defaultPhoto = "uploads/photos/default-profile.jpg";
$finalPhoto = (!empty($result->Photo) && file_exists($result->Photo)) ? $result->Photo : $defaultPhoto;
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Edit Staff Profile | Library System</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet" />

  <style>
    .main-content {
      margin-left: 180px;
      margin-top: 50px;
      padding: 20px;
    }

    .header-line {
      color: #2258d5;
      font-size: 22px;
      font-weight: 600;
    }

    .form-section {
      background: #f9f9f9;
      padding: 25px;
      border-radius: 6px;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }

    .profile-photo {
      width: 100px;
      height: 100px;
      object-fit: cover;
      border-radius: 4px;
    }
  </style>
</head>

<body>
  <?php include('includes/header.php'); ?>

  <div class="container main-content">
    <div class="row mb-4">
      <div class="col-md-12 d-flex justify-content-between align-items-center">
        <h5 class="header-line"><i class="fas fa-user-edit mr-2"></i>Edit Staff Profile</h5>
        <?php if (isset($_SESSION['alogin'])): ?>
          <a href="reg-staffs.php" class="btn btn-secondary"><i class="fas fa-arrow-left"></i> Back</a>
        <?php endif; ?>
      </div>
    </div>

    <div class="row justify-content-center">
      <div class="col-md-9">
        <div class="form-section">
          <form method="post" enctype="multipart/form-data">
            <div class="form-group">
              <label><strong>Staff ID:</strong></label>
              <p><?= htmlentities($result->StaffId); ?></p>
            </div>

            <div class="form-group">
              <label><strong>Registration Date:</strong></label>
              <p><?= htmlentities($result->RegDate); ?></p>
            </div>

            <?php if ($result->UpdationDate): ?>
              <div class="form-group">
                <label><strong>Last Updated:</strong></label>
                <p><?= htmlentities($result->UpdationDate); ?></p>
              </div>
            <?php endif; ?>

            <div class="form-group">
              <label>Status:</label>
              <p>
                <?= $result->Status == 1 ? '<span class="text-success">Active</span>' : '<span class="text-danger">Blocked</span>'; ?>
              </p>
            </div>

            <div class="form-group">
              <label>Full Name</label>
              <input class="form-control" type="text" name="fullname" value="<?= htmlentities($result->FullName); ?>"
                required />
            </div>

            <div class="form-group">
              <label>Mobile Number</label>
              <input class="form-control" type="text" name="mobileno" maxlength="10"
                value="<?= htmlentities($result->MobileNumber); ?>" required />
            </div>

            <div class="form-group">
              <label>Email</label>
              <input class="form-control" type="email" value="<?= htmlentities($result->EmailId); ?>" readonly />
            </div>

            <div class="form-group">
              <label>Address</label>
              <textarea class="form-control" name="address" required><?= htmlentities($result->Address); ?></textarea>
            </div>

            <div class="form-group">
              <label>Department</label>
              <input class="form-control" type="text" value="<?= htmlentities($result->department_name ?? 'N/A'); ?>"
                readonly />
            </div>

            <div class="form-group">
              <label>Designation</label>
              <input class="form-control" type="text" value="<?= htmlentities($result->designation_name ?? 'N/A'); ?>"
                readonly />
            </div>

            <div class="form-group">
              <label>Qualification</label>
              <input class="form-control" type="text" name="qualification"
                value="<?= htmlentities($result->Qualification ?? ''); ?>" />
            </div>

            <div class="form-group">
              <label>Degree</label>
              <input class="form-control" type="text" value="<?= htmlentities($result->degree_name ?? 'N/A'); ?>"
                readonly />
            </div>

            <div class="form-group">
              <label>Joining Date</label>
              <input class="form-control" type="date" name="joiningdate"
                value="<?= htmlentities($result->JoiningDate ?? ''); ?>" />
            </div>

            <div class="form-group">
              <label>Gender</label>
              <input class="form-control" type="text" value="<?= htmlentities($result->gender_name ?? 'N/A'); ?>"
                readonly />
            </div>

            <div class="form-group">
              <label>Upload New ID Proof (optional)</label>
              <input class="form-control" type="file" name="idproof" accept=".pdf,.jpg,.jpeg,.png" />
              <?php
              $idProofPath = "../" . $result->IDProof;
              echo (!empty($result->IDProof) && file_exists($idProofPath))
                ? '<br><a href="' . htmlentities($idProofPath) . '" target="_blank">View Current ID Proof</a>'
                : '<br><span class="text-muted">ID Proof Not Available</span>';
              ?>
            </div>

            <div class="form-group">
              <label>Upload New Photo (optional)</label>
              <input class="form-control" type="file" name="photo" accept=".jpg,.jpeg,.png" />
              <?php
              $photoPath = "../" . $result->Photo;
              echo (!empty($result->Photo) && file_exists($photoPath))
                ? '<br><img src="' . htmlentities($photoPath) . '" class="profile-photo" alt="Current Photo">'
                : '<br><span class="text-muted">Photo Not Available</span>';
              ?>
            </div>

            <div class="text-center mt-4">
              <button type="submit" name="update" class="btn btn-success px-4">
                <i class="fas fa-save"></i> Update Now
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>

  <?php include('includes/footer.php'); ?>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>