<?php

require_once "config.php";

header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
    $cemail = $_GET["cemail"];
    $cpassword = encode($_GET["cpassword"]);
    $query = $conn->query("SELECT * FROM tbmember WHERE ckodecust = '$cemail' AND cpassword = '$cpassword'");
    // $query = $conn->query("SELECT * FROM tbmember WHERE cemail = '$cemail' AND cpassword = '$cpassword'");
    // $query = $conn->query("SELECT * FROM tbmember WHERE cemail = '$cemail'");
    $result = $query->fetch_assoc();
    echo json_encode($result);
    break;
     
    case 'POST':
    $data = json_decode(file_get_contents('php://input'), true);
    try{
        $cemail = $data['cemail'];
        $cpassword = encode($data['cpassword']);
        $conn->query("INSERT INTO tbmember (cemail, cpassword) VALUES ('$cemail', '$cpassword')");    
        echo json_encode(['message' => 'Insert successfully']);
    }catch(Exception $e) {
        http_response_code(409);
        echo json_encode(['message' => 'Insert Failed', "error" => $e]);
    }
    break;

   case 'PUT':
    $data = json_decode(file_get_contents('php://input'), true);
    $cemail = $data["cemail"];
    $old_pw = encode($data["old_password"]);
    $new_pw = encode($data["new_password"]);
    
    $check = $conn->query("SELECT * FROM tbmember WHERE ckodecust = '$cemail' AND cpassword = '$old_pw'");
    
    if ($check->num_rows == 0) {
        http_response_code(406);
        echo json_encode(['error' => 'old password is incorrect']);
    } else {
        $conn->query("UPDATE tbmember SET cpassword = '$new_pw' WHERE ckodecust = '$cemail'");
        echo json_encode(['message' => 'Password updated successfully']);
    }

    break;



    
    case 'DELETE':
    $id = $_GET['id'];
    $conn->query('DELETE FROM books WHERE id=?');
    echo json_encode(['message' => 'Delete successfully']);
    break;

    default:

    // Invalid method
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    break;
}
mysqli_close($conn);
?>