<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: index.php');
    exit;
}
require 'dbconn.php';

$id = $_POST['id'];
$name = $_POST['name'];
$lom_year = $_POST['lom_year'];
$dob = $_POST['dob'];
$address = $_POST['address'];
$blood_group = $_POST['blood_group'];
$email = $_POST['email'];
$phone_r = $_POST['phone_r'];
$phone_o = $_POST['phone_o'];
$mobile1 = $_POST['mobile1'];
$mobile2 = $_POST['mobile2'];
$occupation = $_POST['occupation'];
$designation = $_POST['designation'];
$company_name = $_POST['company_name'];
$company_detail = $_POST['company_detail'];
$achievements = $_POST['achievements'];
$other_detail = $_POST['other_detail'];

$image_path = ''; // Default

// Fetch old image path
$stmtOld = $mysqli->prepare("SELECT image_path FROM treasurer WHERE id = ?");
$stmtOld->bind_param("i", $id);
$stmtOld->execute();
$stmtOld->bind_result($old_image_path);
$stmtOld->fetch();
$stmtOld->close();

// Handle image upload
if (!empty($_FILES['image']['name'])) {
    $image = $_FILES['image'];
    $ext = pathinfo($image['name'], PATHINFO_EXTENSION);

    if (in_array(strtolower($ext), ['jpg', 'jpeg'])) {
        $newName = 'treasurer_' . time() . '.' . $ext;
        $uploadDir = 'uploads/commitee/';
        $targetPath = $uploadDir . $newName;

        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        if (move_uploaded_file($image['tmp_name'], $targetPath)) {
            // Delete old image
            if ($old_image_path && file_exists($old_image_path)) {
                unlink($old_image_path);
            }
            $image_path = $targetPath;
        }
    }
} else {
    $image_path = $old_image_path;
}

// Update query
$stmt = $mysqli->prepare("
    UPDATE treasurer SET 
      name = ?, lom_year = ?, dob = ?, address = ?, blood_group = ?, email = ?,
      phone_r = ?, phone_o = ?, mobile1 = ?, mobile2 = ?, image_path = ?,
      occupation = ?, designation = ?, company_name = ?, company_detail = ?,
      achievements = ?, other_detail = ?
    WHERE id = ?
");

$stmt->bind_param(
  "sisssssssssssssssi",
  $name, $lom_year, $dob, $address, $blood_group, $email,
  $phone_r, $phone_o, $mobile1, $mobile2, $image_path,
  $occupation, $designation, $company_name, $company_detail,
  $achievements, $other_detail, $id
);

if ($stmt->execute()) {
    header("Location: manage_treasurer.php?updated=1");
    exit;
} else {
    echo "Error updating record: " . $stmt->error;
}

$stmt->close();
$mysqli->close();
?>
