<?php
require 'auth.php';
require 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  header("Location: index.php");
  exit;
}

$batId = intval($_POST['battery_id']);
$date = $_POST['service_date'];
$type = $_POST['service_type'];
$tech = htmlspecialchars($_POST['technician']);
$remarks = $_POST['remarks'] ?? null;

// Handle document upload
$documentPath = null;
if (isset($_FILES['document']) && $_FILES['document']['error'] === 0) {
  $uploadDir = "uploads/";
  $fileName = uniqid("doc_") . "_" . basename($_FILES['document']['name']);
  $target = $uploadDir . $fileName;

  if (move_uploaded_file($_FILES['document']['tmp_name'], $target)) {
    $documentPath = $target;
  }
}

$stmt = $pdo->prepare("INSERT INTO service_records (battery_id, service_date, service_type, technician, remarks, document_path) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->execute([$batId, $date, $type, $tech, $remarks, $documentPath]);

header("Location: service_history.php?id=$batId");
exit;