<?php
session_start();
require 'conexion.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 8) {
    header('Location: login.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: dashboard_jefe.php?error=invalid");
    exit;
}

$user_id = $_SESSION['user_id'];
$password = trim($_POST['password'] ?? '');
$confirm  = trim($_POST['confirm_password'] ?? '');

if ($password !== $confirm) {
    header("Location: dashboard_jefe.php?error=nomatch");
    exit;
}

if (strlen($password) < 6) {
    header("Location: dashboard_jefe.php?error=short");
    exit;
}

$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

$sql = "UPDATE accounts SET password=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("si", $hashedPassword, $user_id);

if ($stmt->execute()) {
    // 👇 importante: no borres la sesión, solo redirige
    header("Location: dashboard_jefe.php?success=password");
    exit;
} else {
    header("Location: dashboard_jefe.php?error=fail");
    exit;
}

$stmt->close();
$conn->close();
