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

// Handle image upload
$image_path = '';
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $upload_dir = 'uploads/commitee/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    $filename = basename($_FILES['image']['name']);
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

    if (in_array($ext, ['jpg', 'jpeg'])) {
        $new_filename = uniqid('treasurer_', true) . '.' . $ext;
        $image_path = $upload_dir . $new_filename;

        if (!move_uploaded_file($_FILES['image']['tmp_name'], $image_path)) {
            die('Image upload failed.');
        }
    } else {
        die('Only JPG/JPEG images are allowed.');
    }
}

// Collect form data
$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'];

// Insert query
$stmt = $mysqli->prepare("INSERT INTO treasurer 
(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)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

if (!$stmt) {
    die('Prepare failed: ' . $mysqli->error);
}

$stmt->bind_param("sssssssssssssssss",
    $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
);

if ($stmt->execute()) {
    header("Location: manage_treasurer.php?success=1");
    exit();
} else {
    echo "Insert failed: " . $stmt->error;
}

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